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             shuffled = $.map(allElems, function(){
10                 var random = getRandom(allElems.length),
11                     randEl = $(allElems[random]).clone(true)[0];
12                 allElems.splice(random, 1);
13                 return randEl;
14            });
15  
16         this.each(function(i){
17             $(this).replaceWith($(shuffled[i]));
18         });
19  
20         return $(shuffled);
21  
22     };
23  
24 })(jQuery);

Source

Scroll Page Horizontally With Mouse Wheel

01 $(function() {
02  
03    $("body").mousewheel(function(event, delta) {
04  
05       this.scrollLeft -= (delta * 30);
06  
07       event.preventDefault();
08  
09    });
10  
11 });

Source

Load Only a Section of a Page

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

Source

Highlight Related Label when Input in Focus

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

Source

Highlight All Links To Current Page

1 $(function(){
2     $("a").each(function(){
3        if ($(this).attr("href") == window.location.pathname){
4             $(this).addClass("selected");
5        }
6     });
7 });

Source

Better Broken Image Handling

1 // Replace source
2 $('img').error(function(){
3         $(this).attr('src''missing.png');
4 });
5  
6 // Or, hide them
7 $("img").error(function(){
8         $(this).hide();
9 });

Source

Load Content on Scroll Automatically

01 var loading = false;
02 $(window).scroll(function(){
03     if((($(window).scrollTop()+$(window).height())+250)>=$(document).
04 height()){
05         if(loading == false){
06             loading = true;
07             $('#loadingbar').css("display","block");
08             $.get("load.php?start="+$('#loaded_max').val(),
09 function(loaded){
10                 $('body').append(loaded);
11                 $('#loaded_max').val(parseInt($('#loaded_max')
12 .val())+50);
13                 $('#loadingbar').css("display","none");
14                 loading = false;
15             });
16         }
17     }
18 });
19  
20 $(document).ready(function() {
21     $('#loaded_max').val(50);
22 });

Source

Prevent Multiple Submit of Your Form

01 $(document).ready(function() {
02   $('form').submit(function() {
03     if(typeof jQuery.data(this"disabledOnSubmit") == 'undefined') {
04       jQuery.data(this"disabledOnSubmit", { submited: true });
05       $('input[type=submit], input[type=button]'this).each(function() {
06         $(this).attr("disabled""disabled");
07       });
08       return true;
09     }
10     else
11     {
12       return false;
13     }
14   });
15 });

Source

Make Entire Div Clickable

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

Source

Toggle Text

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

Source

20+个可重复使用的jQuery代码片段的更多相关文章

  1. 50个jquery代码片段(转)

    本文会给你们展示50个jquery代码片段,这些代码能够给你的javascript项目提供帮助.其中的一些代码段是从jQuery1.4.2才开始支持的做法,另一些则是真正有用的函数或方法,他们能够帮助 ...

  2. 可以直接拿来用的15个jQuery代码片段

    jQuery里提供了许多创建交互式网站的方法,在开发Web项目时,开发人员应该好好利用jQuery代码,它们不仅能给网站带来各种动画.特效,还会提高网站的用户体验. 本文收集了15段非常实用的jQue ...

  3. 50个必备的实用jQuery代码段+ 可以直接拿来用的15个jQuery代码片段

    50个必备的实用jQuery代码段+ 可以直接拿来用的15个jQuery代码片段 本文会给你们展示50个jquery代码片段,这些代码能够给你的javascript项目提供帮助.其中的一些代码段是从j ...

  4. 经验分享:10个简单实用的 jQuery 代码片段

    尽管各种 JavaScirpt 框架和库层出不穷,jQuery 仍然是 Web 前端开发中最常用的工具库.今天,向大家分享我觉得在网站开发中10个简单实用的 jQuery 代码片段. 您可能感兴趣的相 ...

  5. 高效Web开发的10个jQuery代码片段(10 JQUERY SNIPPETS FOR EFFICIENT WEB DEVELOPMENT)

    在过去的几年中,jQuery一直是使用最为广泛的JavaScript脚本库.今天我们将为各位Web开发者提供10个最实用的jQuery代码片段,有需要的开发者可以保存起来. 1.检测Internet ...

  6. 10个可以直接拿来用的JQuery代码片段

    jQuery里提供了许多创建交互式网站的方法,在开发Web项目时,开发人员应该好好利用jQuery代码,它们不仅能给网站带来各种动画.特效,还会提高网站的用户体验. 本文收集了10段非常实用的jQue ...

  7. 10个简单实用的 jQuery 代码片段

    尽管各种 JavaScirpt 框架和库层出不穷,jQuery 仍然是 Web 前端开发中最常用的工具库. 今天,向大家分享我觉得在网站开发中10个简单实用的 jQuery 代码片段. 1.平滑滚动到 ...

  8. 【转】jQuery代码片段备用

    在CSDN看到的,记下备用.原文:http://www.csdn.net/article/2013-07-16/2816238-15-jquery-code-snippets-for-develope ...

  9. 一些实用的JQuery代码片段收集

    本文将展示50个非常实用的JQuery代码片段,这些代码能够给你的JavaScript项目提供帮助.其中的一些代码段是从jQuery1.4.2才开始支持的做法,另一些则是真正有用的函数或方法,他们能够 ...

随机推荐

  1. Java命名:

    如果没有public类,就和遵循文件名命名规则: 1.一个.java文件只能有1个public class(暗示可以没有) 2.如果有public class,那么文件名必须与修饰符为public的类 ...

  2. 查看binlog文件的2种方式

    1.使用show binlog events a.获取binlog文件列表 mysql> show binary logs; +------------------+-----------+ | ...

  3. 共享内存shared pool (3):Library cache

    Shared pool物理层面上由许多内存块(chunck)组成.从逻辑功能划分,Shared pool主要由三部分组成:Library cache,Dictionary cache和Control ...

  4. 帮朋友 解决一道 LeetCode QJ上问题

    引言 对于刷题,自己是没能力的. 最经一个朋友同事考我一道数组题 . 也许能当面试分享吧. 娱乐娱乐. 事情的开始是这样的. 前言 题目 截图 大概意思 是 在一个 数组中,找出其中两个不重复出现的元 ...

  5. Socket与TcpClient的区别(转载)

    Socket和TcpClient有什么区别 原文:http://wxwinter.spaces.live.com/blog/cns!C36588978AFC344A!322.entry 回答: &qu ...

  6. 关于TableVIew的上下滚动如何探测其边界

    UITableView is a subclass of UIScrollView, and UITableViewDelegate conforms to UIScrollViewDelegate. ...

  7. java数据结构和算法------顺序查找

    package iYou.neugle.search; public class Sequence_search { public static int SequenceSearch(double[] ...

  8. SQL Server 2008 没有可用于 charge_sys_Log.LDF 的编辑器

    因为上网问题重新装了系统.今天在整 SQL Server  的时候出现了这样一个问题. 因为之前装 SQL Server  的时候没有遇到过这种情况,感觉很新奇.所以详细的记录一下,希望对别人能有一定 ...

  9. background-origin

    background-origin 设置元素背景图片的原始起始位置. 语法: background-origin : border-box | padding-box | content-box; 参 ...

  10. Gentoo 网络接口配置文件说明

    裁剪的Gentoo系统,仅供公司内部使用! [作为备份档案] 网络接口配置:/etc/conf.d/net #设置静态IPconfig_eth0="192.168.1.x/24" ...