20+个可重复使用的jQuery代码片段
jopen
11年前
jQuery已经成为任何web项目的重要组成部分。它为网站提供了交互性的通过移动HTML元素,创建自定义动画,处理事件,选择DOM元素,检索整个document ,让最终用户有一个更好的体验。
在这篇文章中我已经收集了20 +个可重复使用的jQuery代码片段,你可以很容易地复制并直接粘贴到你的项目中。
图片的延迟加载
jQuery(document).ready(function() { jQuery("img.lazy").lazy({ delay: 2000 }); });
预先载入图像
(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)
部分页面刷新
setInterval(function() { $("#refresh").load(location.href+" #refresh>*",""); }, 10000);
延迟动画/效果
$(".alert").delay(2000).fadeOut();
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'); }); } });
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' }); };
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 });
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; } } }); });
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 }); })();
jQuery Accordion
(function($) { var allPanels = $('.accordion > dd').hide(); $('.accordion > dt > a').click(function() { allPanels.slideUp(); $(this).parent().next().slideDown(); return false; }); })(jQuery);
Simple Auto-Playing Slideshow
$("#slideshow > div:gt(0)").hide(); setInterval(function() { $('#slideshow > div:first') .fadeOut(1000) .next() .fadeIn(1000) .end() .appendTo('#slideshow'); }, 3000);
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);
Scroll Page Horizontally With Mouse Wheel
$(function() { $("body").mousewheel(function(event, delta) { this.scrollLeft -= (delta * 30); event.preventDefault(); }); });
Load Only a Section of a Page
$("#mainNav").load("/store #mainNav")
Highlight Related Label when Input in Focus
$("form :input").focus(function() { $("label[for='" + this.id + "']").addClass("labelfocus"); }).blur(function() { $("label").removeClass("labelfocus"); });
Highlight All Links To Current Page
$(function(){ $("a").each(function(){ if ($(this).attr("href") == window.location.pathname){ $(this).addClass("selected"); } }); });
Better Broken Image Handling
// Replace source $('img').error(function(){ $(this).attr('src', 'missing.png'); }); // Or, hide them $("img").error(function(){ $(this).hide(); });
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); });
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; } }); });
Make Entire Div Clickable
$(".myBox").click(function(){ window.location=$(this).find("a").attr("href"); return false; });
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(); });