jquery常用代码

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

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

1.预加载图片

[js]  view plain copy
  1. (function($) {  
  2.   var cache = [];  
  3.   // Arguments are image paths relative to the current page.  
  4.   $.preLoadImages = function() {  
  5.     var args_len = arguments.length;  
  6.     for (var i = args_len; i--;) {  
  7.       var cacheImage = document.createElement('img');  
  8.       cacheImage.src = arguments[i];  
  9.       cache.push(cacheImage);  
  10.     }  
  11.   }  
  12. jQuery.preLoadImages("image1.gif""/path/to/image2.png");  
源码

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

[js]  view plain copy
  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]  view plain copy
  1. $(window).bind("load"function() {  
  2.     // IMAGE RESIZE  
  3.     $('#product_cat_list img').each(function() {  
  4.         var maxWidth = 120;  
  5.         var maxHeight = 120;  
  6.         var ratio = 0;  
  7.         var width = $(this).width();  
  8.         var height = $(this).height();  
  9.         if(width > maxWidth){  
  10.             ratio = maxWidth / width;  
  11.             $(this).css("width", maxWidth);  
  12.             $(this).css("height", height * ratio);  
  13.             height = height * ratio;  
  14.         }  
  15.         var width = $(this).width();  
  16.         var height = $(this).height();  
  17.         if(height > maxHeight){  
  18.             ratio = maxHeight / height;  
  19.             $(this).css("height", maxHeight);  
  20.             $(this).css("width", width * ratio);  
  21.             width = width * ratio;  
  22.         }  
  23.     });  
  24.     //$("#contentpage img").show();  
  25.     // IMAGE RESIZE  
  26. });  
源码

4.返回页面顶部

[js]  view plain copy
  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]  view plain copy
  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]  view plain copy
  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]  view plain copy
  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]  view plain copy
  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]  view plain copy
  1. $(document).ready(function(){  
  2.     $(".thumbs img").fadeTo("slow", 0.6); // This sets the opacity of the thumbs to fade down to 60% when the page loads  
  3.     $(".thumbs img").hover(function(){  
  4.         $(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover  
  5.     },function(){  
  6.         $(this).fadeTo("slow", 0.6); // This should set the opacity back to 60% on mouseout  
  7.     });  
  8. });  
源码

10.清空表单数据

[js]  view plain copy
  1. function clearForm(form) {  
  2.   // iterate over all of the inputs for the form  
  3.   // element that was passed in  
  4.   $(':input', form).each(function() {  
  5.     var type = this.type;  
  6.     var tag = this.tagName.toLowerCase(); // normalize case  
  7.     // it's ok to reset the value attr of text inputs,  
  8.     // password inputs, and textareas  
  9.     if (type == 'text' || type == 'password' || tag == 'textarea')  
  10.       this.value = "";  
  11.     // checkboxes and radios need to have their checked state cleared  
  12.     // but should *not* have their 'value' changed  
  13.     else if (type == 'checkbox' || type == 'radio')  
  14.       this.checked = false;  
  15.     // select elements need to have their 'selectedIndex' property set to -1  
  16.     // (this works for both single and multiple select elements)  
  17.     else if (tag == 'select')  
  18.       this.selectedIndex = -1;  
  19.   });  
  20. };  
源码

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

[js]  view plain copy
  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]  view plain copy
  1. //change event on password1 field to prompt new input  
  2. $('#password1').change(function() {  
  3.         //dynamically create new input and insert after password1  
  4.         $("#password1").append("");  
  5. });  
源码

13.让整个Div可点击

[js]  view plain copy
  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]  view plain copy
  1. var maxHeight = 0;  
  2. $("div").each(function(){  
  3.    if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }  
  4. });  
  5. $("div").height(maxHeight);  
源码

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

[js]  view plain copy
  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. });  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值