`
wb1991wb
  • 浏览: 151708 次
  • 来自: 上海
社区版块
存档分类
最新评论

常用的15个jQuery代码片段

 
阅读更多

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

本文收集了15段非常实用的jQuery代码片段,你可以直接复制黏贴到代码里,但请开发者注意了,要理解代码再使用哦。下面就让我们一起来享受jQuery代码的魅力之处吧。

1.预加载图片

Js代码 复制代码
  1. (function($) {   
  2.   var cache = [];   
  3.      
  4. // Arguments are image paths relative to the current page.   
  5.   $.preLoadImages = function() {   
  6.     var args_len = arguments.length;   
  7.     for (var i = args_len; i--;) {   
  8.       var cacheImage = document.createElement('img');   
  9.       cacheImage.src = arguments[i];   
  10.       cache.push(cacheImage);   
  11.     }   
  12.   }   
  13. jQuery.preLoadImages("image1.gif""/path/to/image2.png");  
(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.preLoadImages("image1.gif", "/path/to/image2.png");

 源码

2. 让页面中的每个元素都适合在移动设备上展示

Js代码 复制代码
  1. var scr = document.createElement('script');   
  2. scr.setAttribute('src''https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js');   
  3. document.body.appendChild(scr);   
  4. scr.onload = function(){   
  5.     $('div').attr('class''').attr('id''').css({   
  6.         'margin' : 0,   
  7.         'padding' : 0,   
  8.         'width''100%',   
  9.         'clear':'both'  
  10.     });   
  11. };  
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'
    });
};

 源码

3.图像等比例缩放

Js代码 复制代码
  1. $(window).bind("load"function() {   
  2.        
  3. // IMAGE RESIZE   
  4.     $('#product_cat_list img').each(function() {   
  5.         var maxWidth = 120;   
  6.         var maxHeight = 120;   
  7.         var ratio = 0;   
  8.         var width = $(this).width();   
  9.         var height = $(this).height();   
  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.        
  26. //$("#contentpage img").show();   
  27.        
  28. // IMAGE RESIZE   
  29. });  
$(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
});

 源码

4.返回页面顶部

Js代码 复制代码
  1. // Back To Top   
  2. $(document).ready(function(){   
  3.   $('.top').click(function() {    
  4.      $(document).scrollTo(0,500);    
  5.   });   
  6. });   
  7. //Create a link defined with the class .top   
  8. <a href="#" class="top">Back To Top</a>  
// Back To Top
$(document).ready(function(){
  $('.top').click(function() { 
     $(document).scrollTo(0,500); 
  });
});
//Create a link defined with the class .top
<a href="#" class="top">Back To Top</a>

 源码

5.使用jQuery打造手风琴式的折叠效果

Js代码 复制代码
  1. var accordion = {   
  2.      init: function(){   
  3.            var $container = $('#accordion');   
  4.            $container.find('li:not(:first) .details').hide();   
  5.            $container.find('li:first').addClass('active');   
  6.            $container.on('click','li a',function(e){   
  7.                   e.preventDefault();   
  8.                   var $this = $(this).parents('li');   
  9.                   if($this.hasClass('active')){   
  10.                          if($('.details').is(':visible')) {   
  11.                                 $this.find('.details').slideUp();   
  12.                          } else {   
  13.                                 $this.find('.details').slideDown();   
  14.                          }   
  15.                   } else {   
  16.                          $container.find('li.active .details').slideUp();   
  17.                          $container.find('li').removeClass('active');   
  18.                          $this.addClass('active');   
  19.                          $this.find('.details').slideDown();   
  20.                   }   
  21.            });   
  22.      }   
  23. };  
var accordion = {
     init: function(){
           var $container = $('#accordion');
           $container.find('li:not(:first) .details').hide();
           $container.find('li:first').addClass('active');
           $container.on('click','li a',function(e){
                  e.preventDefault();
                  var $this = $(this).parents('li');
                  if($this.hasClass('active')){
                         if($('.details').is(':visible')) {
                                $this.find('.details').slideUp();
                         } else {
                                $this.find('.details').slideDown();
                         }
                  } else {
                         $container.find('li.active .details').slideUp();
                         $container.find('li').removeClass('active');
                         $this.addClass('active');
                         $this.find('.details').slideDown();
                  }
           });
     }
};

6.通过预加载图片廊中的上一幅下一幅图片来模仿Facebook的图片展示方式

Js代码 复制代码
  1. var nextimage = "/images/some-image.jpg";   
  2. $(document).ready(function(){   
  3. window.setTimeout(function(){   
  4. var img = $("").attr("src", nextimage).load(function(){   
  5. //all done   
  6. });   
  7. }, 100);   
  8. });  
var nextimage = "/images/some-image.jpg";
$(document).ready(function(){
window.setTimeout(function(){
var img = $("").attr("src", nextimage).load(function(){
//all done
});
}, 100);
});

 源码

7.使用jQuery和Ajax自动填充选择框

Js代码 复制代码
  1. $(function(){   
  2. $("select#ctlJob").change(function(){   
  3. $.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){   
  4. var options = '';   
  5. for (var i = 0; i < j.length; i++) {   
  6. options += '   
  7. ' + j[i].optionDisplay + '  
  8. ';   
  9. }   
  10. $("select#ctlPerson").html(options);   
  11. })   
  12. })   
  13. })  
$(function(){
$("select#ctlJob").change(function(){
$.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '
' + j[i].optionDisplay + '
';
}
$("select#ctlPerson").html(options);
})
})
})

 源码

8.自动替换丢失的图片

Js代码 复制代码
  1. // Safe Snippet   
  2. $("img").error(function () {   
  3.     $(this).unbind("error").attr("src""missing_image.gif");   
  4. });   
  5. // Persistent Snipper   
  6. $("img").error(function () {   
  7.     $(this).attr("src""missing_image.gif");   
  8. });  
// Safe Snippet
$("img").error(function () {
    $(this).unbind("error").attr("src", "missing_image.gif");
});
// Persistent Snipper
$("img").error(function () {
    $(this).attr("src", "missing_image.gif");
});

 源码

9.在鼠标悬停时显示淡入/淡出特效

Js代码 复制代码
  1. $(document).ready(function(){   
  2.     $(".thumbs img").fadeTo("slow", 0.6);   
  3. // This sets the opacity of the thumbs to fade down to 60% when the page loads   
  4.     $(".thumbs img").hover(function(){   
  5.         $(this).fadeTo("slow", 1.0);   
  6. // This should set the opacity to 100% on hover   
  7.     },function(){   
  8.         $(this).fadeTo("slow", 0.6);   
  9. // This should set the opacity back to 60% on mouseout   
  10.     });   
  11. });  
$(document).ready(function(){
    $(".thumbs img").fadeTo("slow", 0.6);
// This sets the opacity of the thumbs to fade down to 60% when the page loads
    $(".thumbs img").hover(function(){
        $(this).fadeTo("slow", 1.0);
// This should set the opacity to 100% on hover
    },function(){
        $(this).fadeTo("slow", 0.6);
// This should set the opacity back to 60% on mouseout
    });
});
 源码
10.清空表单数据
Js代码 复制代码
  1. function clearForm(form) {   
  2.      
  3. // iterate over all of the inputs for the form   
  4.      
  5. // element that was passed in   
  6.   $(':input', form).each(function() {   
  7.     var type = this.type;   
  8.     var tag = this.tagName.toLowerCase();   
  9. // normalize case   
  10.        
  11. // it's ok to reset the value attr of text inputs,   
  12.        
  13. // password inputs, and textareas   
  14.     if (type == 'text' || type == 'password' || tag == 'textarea')   
  15.       this.value = "";   
  16.     // checkboxes and radios need to have their checked state cleared   
  17.     // but should *not* have their 'value' changed   
  18.     else if (type == 'checkbox' || type == 'radio')   
  19.       this.checked = false;   
  20.     // select elements need to have their 'selectedIndex' property set to -1   
  21.     // (this works for both single and multiple select elements)   
  22.     else if (tag == 'select')   
  23.       this.selectedIndex = -1;   
  24.   });   
  25. };  
function clearForm(form) {
  
// iterate over all of the inputs for the form
  
// element that was passed in
  $(':input', form).each(function() {
    var type = this.type;
    var tag = this.tagName.toLowerCase();
// normalize case
    
// it's ok to reset the value attr of text inputs,
    
// password inputs, and textareas
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = "";
    // checkboxes and radios need to have their checked state cleared
    // but should *not* have their 'value' changed
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    // select elements need to have their 'selectedIndex' property set to -1
    // (this works for both single and multiple select elements)
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};
 源码

 11.预防对表单进行多次提交

Js代码 复制代码
  1. $(document).ready(function() {   
  2.   $('form').submit(function() {   
  3.     if(typeof jQuery.data(this"disabledOnSubmit") == 'undefined') {   
  4.       jQuery.data(this"disabledOnSubmit", { submited: true });   
  5.       $('input[type=submit], input[type=button]'this).each(function() {   
  6.         $(this).attr("disabled""disabled");   
  7.       });   
  8.       return true;   
  9.     }   
  10.     else  
  11.     {   
  12.       return false;   
  13.     }   
  14.   });   
  15. });  
$(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;
    }
  });
});

 源码

 

12.动态添加表单元素

Js代码 复制代码
  1. //change event on password1 field to prompt new input   
  2. $('#password1').change(function() {   
  3.            
  4. //dynamically create new input and insert after password1   
  5.         $("#password1").append("");   
  6. });  
//change event on password1 field to prompt new input
$('#password1').change(function() {
        
//dynamically create new input and insert after password1
        $("#password1").append("");
});

 源码

13.让整个Div可点击

Js代码 复制代码
  1. blah blah blah. link   
  2. The following lines of jQuery will make the entire div clickable: $(".myBox").click(function(){ window.location=$(this).find("a").attr("href"); return false; });  
blah blah blah. link
The following lines of jQuery will make the entire div clickable: $(".myBox").click(function(){ window.location=$(this).find("a").attr("href"); return false; });

 源码

14.平衡高度或Div元素

Js代码 复制代码
  1. var maxHeight = 0;   
  2. $("div").each(function(){   
  3.    if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }   
  4. });   
  5. $("div").height(maxHeight);  
var maxHeight = 0;
$("div").each(function(){
   if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
});
$("div").height(maxHeight);

 源码

15. 在窗口滚动时自动加载内容

Js代码 复制代码
  1. var loading = false;   
  2. $(window).scroll(function(){   
  3.     if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){   
  4.         if(loading == false){   
  5.             loading = true;   
  6.             $('#loadingbar').css("display","block");   
  7.             $.get("load.php?start="+$('#loaded_max').val(), function(loaded){   
  8.                 $('body').append(loaded);   
  9.                 $('#loaded_max').val(parseInt($('#loaded_max').val())+50);   
  10.                 $('#loadingbar').css("display","none");   
  11.                 loading = false;   
  12.             });   
  13.         }   
  14.     }   
  15. });   
  16. $(document).ready(function() {   
  17.     $('#loaded_max').val(50);   
  18. });  
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);
});

 via:codegeekz

分享到:
评论

相关推荐

    常用的几个JQuery代码片段

    本文主要介绍了常用的几个JQuery代码片段。具有很好的参考价值。下面跟着小编一起来看下吧

    jQuery常用代码片段

    NULL 博文链接:https://dodomail.iteye.com/blog/1906673

    15个常用的jquery代码片段

    主要介绍了15个常用的jquery代码片段,对大家学习jquery程序设计有所帮助,需要的朋友可以参考下

    一些实用的jQuery代码片段收集

    下边这些jQuery片段只是很少的一部分,如果您在学习过程中也遇到过一些常用的jQuery代码,欢迎分享。下边就让我们看看这些有代码片段。 1.jQuery得到用户IP: 代码如下: $.getJSON(...

    web前端开发JQuery常用实例代码片段(50个)

    本文给大家展示50个jquery代码片段,这些代码能够给你的javascript项目提供帮助。其中的一些代码段是从jQuery1.4.2才开始支持的做法,另一些则是真正有用的函数或方法,他们能够帮助你又快又好地把事情完成。这些都...

    query mobile 代码助手

    将常用的组件分类成page页面、content...对于JQuery Mobile的初学者,可以通过生成代码片段进行练习,学习JQuery Mobile所有组件的属性和接口,对于JQuery Mobile开发人员,jQM代码助手可以快速生成代码,提高效率。

    工作中常用的js、jquery自定义扩展函数代码片段汇总

    本文主要对工作中常用的js、jquery自定义扩展函数代码片段进行了分享,具有很好的参考价值,需要的朋友一起来看下吧

    史上最全Hbuilder 代码片段snippets,支持Thinkphp

    Hbuilder代码片段,急速开发,支持html,css,js,Jquery和Thinkphp

    分享100个直接可以拿来用的JavaScript实用功能代码片段

    把平时网站上常用的一些实用功能代码片段通通收集起来,方面网友们学习使用,利用好的话可以加快网友们的开发速度,提高工作效率。

    Sublime-Snippet-Collect:收集Sublime代码片段(Snippet)

    下面是一些常用的代码片段收集(欢迎大家pull request) 语言 JavaScript HTML 建议使用 CSS 建议使用 框架和库 AngularJS Angular UI AngularJS Sublime Package JQuery jQuery Snippets Pack Bootstrap3 Bootstrap 3...

    java开发在工作中代码搜集

    该资料为chm电子书,为开发工作中遇到的工具...现已搜集接近一百个工具类、十多种功能代码、各种第三方类库搜集、springBoot使用文档、四种语法类文档、五个数据对照表、各种设计模式文档、js(jquery)常用操作及代码片段

    jQuery、zepto、js常用小技巧

    以下只为记录自己工作常用的片段和心得, 如有问题请指正, 多谢~ jQuery/zepto判断元素是否存在 // 判断长度是否存在, 正确 if ($elem.length) { } // 错误, 因为空数组也是true if ($elem) { } 合理判断数据类型 ...

    Sublime Text常用插件

    资源包含9种Sublime Text常用的插件,AndyJS2Plus-master(js代码智能提醒)atom-jquery-snippets-master(代码片段功能)ColorPicker(颜色拾取器)csscomb.js-master(css格式化)Emmet(不多解释,都懂)JsFormat...

    做好七件事帮你提升jQuery的性能

    1. Append Outside of Loops 凡是触及到DOM都是有代价的。如果你向DOM当中附加大量的元素,你会想一次性将它们...一个常用的技巧是利用文档片段(document fragment)。在循环的每一次迭代当中,将元素附加到片段而不是

Global site tag (gtag.js) - Google Analytics