可以直接拿来用的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");  

 源码

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. };  

 源码

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. });  

 源码

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>  

 源码

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. };  

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. });  

 源码

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. })  

 源码

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. });  

 源码

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. });  
 源码
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. };  
 源码

 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. });  

 源码

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. });  

 源码

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; });  

 源码

14.平衡高度或Div元素

Js代码
  1. var maxHeight = 0;  
  2. $("div").each(function(){  
  3.    if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }  
  4. });  
  5. $("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. }); 
原文地址:https://www.cnblogs.com/RedRoshan/p/3569164.html