Home > Web Front-end > JS Tutorial > Share 15 jquery tips that everyone is familiar with_jquery

Share 15 jquery tips that everyone is familiar with_jquery

WBOY
Release: 2016-05-16 15:28:13
Original
1563 people have browsed it

15 well-known jquery tips to help improve your jQuery application, share with everyone

  • Back to top button
  • Image preloading
  • Determine whether the image has been loaded
  • Automatically repair damaged images
  • Hover switch class
  • Disable input
  • Stop loading links
  • toggle fade/slide
  • Simple accordion
  • Make two DIVs the same height
  • Open external link in browser tab/new window
  • Get elements based on text
  • Trigger of visible changes
  • Ajax call error handling
  • Chain operation

1. Back to top button

Using the animate and scrollTop methods in jQuery, you don’t need to use plug-ins to create simple scroll-to-top animations.

// Back to top

$('.top').click(function (e) {

 e.preventDefault();

 $('html, body').animate({scrollTop: 0}, 800);

});

<!-- Create an anchor tag -->

<a class="top" href="#">Back to top</a>

Copy after login

Change the position you want to scroll to by using the value of scrollTop. Essentially that's what you do: let the page scroll for the next 800 milliseconds until it scrolls to the top of the document.

Note: Let’s take a look at some of scrollTop’s naughty behaviors.

2. Image preloading

If your web page uses a lot of hidden image files (for example: images displayed on mouseover), then preloading of images makes sense:

$.preloadImages = function () {
 for (var i = 0; i < arguments.length; i++) {
 $('<img>').attr('src', arguments[i]);
 }
}; 
$.preloadImages('img/hover-on.png', 'img/hover-off.png');
Copy after login

3. Determine whether the image is loaded

Sometimes you may need to check whether the image has been loaded so that you can continue to execute the corresponding js code:

$('img').load(function () {
 console.log('image load successful');
});
Copy after login

You can also check if a specific image has been loaded and replaced by an tag with an Id or class.

4. Automatically repair damaged images

If you happen to find broken image links on your site, it can be a pain to replace them one by one. This simple code can save a lot of trouble:

$('img').on('error', function () {
 if(!$(this).hasClass('broken-image')) {
 $(this).prop('src', 'img/broken.png').addClass('broken-image');
 }
});
Copy after login

Even if you don’t have any broken links, adding this code will have no impact.

5. Hover switching class

Let’s say you want to change the visual effect of an element on your page when a user hovers over it. When the user mouses over an element, you can add a class to the element and remove the class when the mouse stops hovering:

$('.btn').hover(function () {
 $(this).addClass('hover');
}, function () {
 $(this).removeClass('hover');
});
Copy after login

If you want a simpler way to use the toggleClass method, just add the necessary CSS:

$('.btn').hover(function () {
 $(this).toggleClass('hover');
});
Copy after login

Note: CSS is a quick solution in this case, but it’s still worth knowing.

6. Disable input

Sometimes you may need to use a form's submit button or an input field until the user performs an action (for example: checking the "I have read the terms" checkbox). Set the disabled attribute on your input box, and then enable it when you need it:

Copy code The code is as follows:
$('input[type="submit"]').prop ('disabled', true);

All you need to do is run the prop method on the input box again, but set the disabled value to false:

Copy code The code is as follows:
$('input[type="submit"]').prop ('disabled', false);

7. Stop loading links

Sometimes you don't want to link to a specific web page or reload the page; you may want them to do something else, like trigger some other script. Here are tips to prevent breach of contract actions:

$('a.no-link').click(function (e) {
 e.preventDefault();
});
Copy after login

8. toggle fade/slide

Sliding and fade-in/fade-out are animations that we often use heavily in jQuery. You may only want to display an element when the user performs certain click events, in which case a fade in/out or sliding method is required. But if you need that element to appear when you click it for the first time and disappear when you click it for the second time, the code is as follows:

// Fade
$('.btn').click(function () {
 $('.element').fadeToggle('slow');
});
// Toggle
$('.btn').click(function () {
 $('.element').slideToggle('slow');
});
Copy after login

9. Simple accordion

Here’s a quick and easy way to create an accordion:

// Close all panels
$('#accordion').find('.content').hide();
// Accordion
$('#accordion').find('.accordion-header').click(function () {
 var next = $(this).next();
 next.slideToggle('fast');
 $('.content').not(next).slideUp('fast');
 return false;
});
Copy after login

通过添加这个脚本,你需要做的则是必要的HTML操作在你的页面上。

10、使两个DIV同等高度

有时你会想要两个DIV有相同的高度,无论他们都有什么内容:

复制代码 代码如下:
$('.div').css('min-height', $('.main-div').height());

这个例子设置了DIV的最小高度,这意味着它的高度只可以比这个设置的高度大而不能小。然而,一个更灵活的方法是循环的一组元素,并设置将最高元素的高度作为高度:

var $columns = $('.column');
var height = 0;
$columns.each(function () {
 if ($(this).height() > height) {
 height = $(this).height();
 }
});
$columns.height(height);
Copy after login

如果你想要所有的列有相同的高度:

var $rows = $('.same-height-columns');
$rows.each(function () {
 $(this).find('.column').height($(this).height());
});
Copy after login

11、在浏览器标签/新窗口打开外部链接

在新的浏览器标签或窗口中打开外部链接,并确保在同一个标签或窗口中打开的是同一个源的链接:

$('a[href^="http"]').attr('target', '_blank');
$('a[href^="//"]').attr('target', '_blank');
$('a[href^="' + window.location.origin + '"]').attr('target', '_self');
Copy after login

备注:window.location.origin 在IE10不工作。

12、根据文本获取元素

通过jQuery中的contains()选择器,你能找到一个元素内的文本内容。如果文本不存在,则这个元素将被隐藏:

var search = $('#search').val();
$('div:not(:contains("' + search + '"))').hide();
Copy after login

13、可见变化的触发

当用户不再聚焦或者重新聚焦一个标签时触发javascript脚本:

$(document).on('visibilitychange', function (e) {
 if (e.target.visibilityState === "visible") {
 console.log('Tab is now in view!');
 } else if (e.target.visibilityState === "hidden") {
 console.log('Tab is now hidden!');
 }
});
Copy after login

14、Ajax调用错误处理

当一个Ajax调用返回一个404或500的错误时,将执行该错误处理。如果该处理未定义,则其他jQuery代码便可能不会执行了。定义一个全局Ajax错误处理程序:

$(document).ajaxError(function (e, xhr, settings, error) {
 console.log(error);
});
Copy after login

15、链式操作

jQuery允许通过链式操作来减轻反复查询DOM和创建多个jQuery对象的过程。比如下面是你的方法调用:

$('#elem').show();
$('#elem').html('bla');
$('#elem').otherStuff();
Copy after login

这代码可以通过链式大大的提高:

$('#elem')
 .show()
 .html('bla')
 .otherStuff();
Copy after login

另一个方法是在一个可变的元素缓存($作为前置):

var $elem = $('#elem');
$elem.hide();
$elem.html('bla');
$elem.otherStuff();
Copy after login

链式和jQuery缓存方法是最好的做法,导致更短、更快的代码。

以上就是本文的全部内容,希望帮助大家提高jQuery应用能力。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template