20+個可重復使用的jQuery代碼片段

jopen 10年前發布 | 31K 次閱讀 jQuery Ajax框架

jQuery已經成為任何web項目的重要組成部分。它為網站提供了交互性的通過移動HTML元素,創建自定義動畫,處理事件,選擇DOM元素,檢索整個document ,讓最終用戶有一個更好的體驗。

在這篇文章中我已經收集了20 +個可重復使用的jQuery代碼片段,你可以很容易地復制并直接粘貼到你的項目中。

Reusable jQuery Code Snippets for Developers

圖片的延遲加載

jQuery(document).ready(function() {
    jQuery("img.lazy").lazy({
        delay: 2000
    });
});

Source

預先載入圖像

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

Source

部分頁面刷新

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

Source

延遲動畫/效果

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

Source

Open external link in New Window

$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if(!a.test(this.href)) {
       $(this).click(function(event) {
           event.preventDefault();
           event.stopPropagation();
           window.open(this.href, '_blank');
       });
   }
});

Source

Make Everything Mobile Friendly

var scr = document.createElement('script');
scr.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/
jquery.min.js');
document.body.appendChild(scr);

scr.onload = function(){

    $('div').attr('class', '').attr('id', '').css({
        'margin' : 0,
        'padding' : 0,
        'width': '100%',
        'clear':'both'
    });
};

Source

Image Resize Using jQuery

$(window).bind("load", function() {
    // IMAGE RESIZE
    $('#product_cat_list img').each(function() {
        var maxWidth = 120;
        var maxHeight = 120;
        var ratio = 0;
        var width = $(this).width();
        var height = $(this).height();

        if(width > maxWidth){
            ratio = maxWidth / width;
            $(this).css("width", maxWidth);
            $(this).css("height", height * ratio);
            height = height * ratio;
        }
        var width = $(this).width();
        var height = $(this).height();
        if(height > maxHeight){
            ratio = maxHeight / height;
            $(this).css("height", maxHeight);
            $(this).css("width", width * ratio);
            width = width * ratio;
        }
    });
    //$("#contentpage img").show();
    // IMAGE RESIZE
});

Source

Smooth Scrolling

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
 && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

Source

Window load event with minimum delay

(function fn() {

  fn.now = +new Date;

  $(window).load(function() {

     if (+new Date - fn.now < 500) setTimeout(fn, 500);

         // Do something

  });

})();

Source

jQuery Accordion

(function($) {

  var allPanels = $('.accordion > dd').hide();

  $('.accordion > dt > a').click(function() {
    allPanels.slideUp();
    $(this).parent().next().slideDown();
    return false;
  });

})(jQuery);

Source

Simple Auto-Playing Slideshow

$("#slideshow > div:gt(0)").hide();

setInterval(function() { 
  $('#slideshow > div:first')
    .fadeOut(1000)
    .next()
    .fadeIn(1000)
    .end()
    .appendTo('#slideshow');
},  3000);

Source

Shuffle DOM Elements

(function($){

    $.fn.shuffle = function() {

        var allElems = this.get(),
            getRandom = function(max) {
                return Math.floor(Math.random() * max);
            },
            shuffled = $.map(allElems, function(){
                var random = getRandom(allElems.length),
                    randEl = $(allElems[random]).clone(true)[0];
                allElems.splice(random, 1);
                return randEl;
           });

        this.each(function(i){
            $(this).replaceWith($(shuffled[i]));
        });

        return $(shuffled);

    };

})(jQuery);

Source

Scroll Page Horizontally With Mouse Wheel

$(function() {

   $("body").mousewheel(function(event, delta) {

      this.scrollLeft -= (delta * 30);

      event.preventDefault();

   });

});

Source

Load Only a Section of a Page

$("#mainNav").load("/store #mainNav")

Source

Highlight Related Label when Input in Focus

$("form :input").focus(function() {
  $("label[for='" + this.id + "']").addClass("labelfocus");
}).blur(function() {
  $("label").removeClass("labelfocus");
});

Source

Highlight All Links To Current Page

$(function(){
    $("a").each(function(){
       if ($(this).attr("href") == window.location.pathname){
            $(this).addClass("selected");
       }
    });
});

Source

Better Broken Image Handling

// Replace source
$('img').error(function(){
        $(this).attr('src', 'missing.png');
});

// Or, hide them
$("img").error(function(){
        $(this).hide();
});

Source

Load Content on Scroll Automatically

var loading = false;
$(window).scroll(function(){
    if((($(window).scrollTop()+$(window).height())+250)>=$(document).
height()){
        if(loading == false){
            loading = true;
            $('#loadingbar').css("display","block");
            $.get("load.php?start="+$('#loaded_max').val(), 
function(loaded){
                $('body').append(loaded);
                $('#loaded_max').val(parseInt($('#loaded_max')
.val())+50);
                $('#loadingbar').css("display","none");
                loading = false;
            });
        }
    }
});

$(document).ready(function() {
    $('#loaded_max').val(50);
});

Source

Prevent Multiple Submit of Your Form

$(document).ready(function() {
  $('form').submit(function() {
    if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') {
      jQuery.data(this, "disabledOnSubmit", { submited: true });
      $('input[type=submit], input[type=button]', this).each(function() {
        $(this).attr("disabled", "disabled");
      });
      return true;
    }
    else
    {
      return false;
    }
  });
});

Source

Make Entire Div Clickable

$(".myBox").click(function(){
     window.location=$(this).find("a").attr("href"); 
     return false;
});

Source

Toggle Text

$("#more-less-options-button").click(function() {
     var txt = $("#extra-options").is(':visible') ? 'more options' : 'less 
options';
     $("#more-less-options-button").text(txt);
     $("#extra-options").slideToggle();
});

Source

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!