20+个可重复使用的jQuery代码片段

jQuery已经成为任何web项目的重要组成部分。它为网站提供了交互性的通过移动HTML元素,创建自定义动画,处理事件,选择DOM元素,检索整个document ,让最终用户有一个更好的体验。

在这篇文章中我已经收集了20 +个可重复使用的jQuery代码片段,你可以很容易地复制并直接粘贴到你的项目中。

 

图片的延迟加载

1 jQuery(document).ready(function() {
2     jQuery("img.lazy").lazy({
3         delay: 2000
4     });
5 });

Source

预先载入图像

01 (function($) {
02   var cache = [];
03   // Arguments are image paths relative to the current page.
04   $.preLoadImages = function() {
05     var args_len = arguments.length;
06     for (var i = args_len; i--;) {
07       var cacheImage = document.createElement('img');
08       cacheImage.src = arguments[i];
09       cache.push(cacheImage);
10     }
11   }
12 })(jQuery)

Source

部分页面刷新

1 setInterval(function() {
2     $("#refresh").load(location.href+" #refresh>*","");
3 }, 10000);

Source

延迟动画/效果

1 $(".alert").delay(2000).fadeOut();

Source

Open external link in New Window

01 $('a').each(function() {
02    var a = new RegExp('/' + window.location.host + '/');
03    if(!a.test(this.href)) {
04        $(this).click(function(event) {
05            event.preventDefault();
06            event.stopPropagation();
07            window.open(this.href, '_blank');
08        });
09    }
10 });

Source

Make Everything Mobile Friendly

01 var scr = document.createElement('script');
02 scr.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/
03 jquery.min.js');
04 document.body.appendChild(scr);
05  
06 scr.onload = function(){
07  
08     $('div').attr('class', '').attr('id', '').css({
09         'margin' : 0,
10         'padding' : 0,
11         'width': '100%',
12         'clear':'both'
13     });
14 };

Source

Image Resize Using jQuery

01 $(window).bind("load", function() {
02     // IMAGE RESIZE
03     $('#product_cat_list img').each(function() {
04         var maxWidth = 120;
05         var maxHeight = 120;
06         var ratio = 0;
07         var width = $(this).width();
08         var height = $(this).height();
09  
10         if(width > maxWidth){
11             ratio = maxWidth / width;
12             $(this).css("width", maxWidth);
13             $(this).css("height", height * ratio);
14             height = height * ratio;
15         }
16         var width = $(this).width();
17         var height = $(this).height();
18         if(height > maxHeight){
19             ratio = maxHeight / height;
20             $(this).css("height", maxHeight);
21             $(this).css("width", width * ratio);
22             width = width * ratio;
23         }
24     });
25     //$("#contentpage img").show();
26     // IMAGE RESIZE
27 });

Source

Smooth Scrolling

01 $(function() {
02   $('a[href*=#]:not([href=#])').click(function() {
03     if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
04  && location.hostname == this.hostname) {
05       var target = $(this.hash);
06       target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
07       if (target.length) {
08         $('html,body').animate({
09           scrollTop: target.offset().top
10         }, 1000);
11         return false;
12       }
13     }
14   });
15 });

Source

Window load event with minimum delay

01 (function fn() {
02  
03   fn.now = +new Date;
04  
05   $(window).load(function() {
06  
07      if (+new Date - fn.now < 500) setTimeout(fn, 500);
08  
09          // Do something
10  
11   });
12  
13 })();

Source

jQuery Accordion

01 (function($) {
02  
03   var allPanels = $('.accordion > dd').hide();
04  
05   $('.accordion > dt > a').click(function() {
06     allPanels.slideUp();
07     $(this).parent().next().slideDown();
08     return false;
09   });
10  
11 })(jQuery);

Source

Simple Auto-Playing Slideshow

01 $("#slideshow > div:gt(0)").hide();
02  
03 setInterval(function() {
04   $('#slideshow > div:first')
05     .fadeOut(1000)
06     .next()
07     .fadeIn(1000)
08     .end()
09     .appendTo('#slideshow');
10 },  3000);

Source

Shuffle DOM Elements

01 (function($){
02  
03     $.fn.shuffle = function() {
04  
05         var allElems = this.get(),
06             getRandom = function(max) {
07                 return Math.floor(Math.random() * max);
08             },
09

你可能感兴趣的:(jquery)