直接拿来用的15个jQuery代码片段


Posted in Javascript onSeptember 23, 2015

发表过的一篇《10个超级有用的PHP代码片段果断收藏》吗?本文笔者将继续为你奉上15个超级有用的jQuery代码片段。

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

直接拿来用的15个jQuery代码片段

下面就让我们一起来享受jQuery代码的魅力之处吧。

1.预加载图片

(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. 让页面中的每个元素都适合在移动设备上展示

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.图像等比例缩放

$(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.返回页面顶部

// 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打造手风琴式的折叠效果

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的图片展示方式

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自动填充选择框

$(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.自动替换丢失的图片

// 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.在鼠标悬停时显示淡入/淡出特效

$(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.清空表单数据

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.预防对表单进行多次提交

$(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.动态添加表单元素

//change event on password1 field to prompt new input 
$('#password1').change(function() { 
    //dynamically create new input and insert after password1 
    $("#password1").append(""); 
});

 

13.让整个Div可点击

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元素

var maxHeight = 0; 
$("div").each(function(){ 
  if ($(this).height() > maxHeight) { maxHeight = $(this).height(); } 
}); 
$("div").height(maxHeight);

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

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

本文收集的这15段非常实用的jQuery代码片段,你可以直接复制黏贴到代码里,但请开发者注意了,要理解代码再使用哦。

Javascript 相关文章推荐
javascript 折半查找字符在数组中的位置(有序列表)
Dec 09 Javascript
js 可拖动列表实现代码
Dec 13 Javascript
Jquery Uploadify上传带进度条的简单实例
Feb 12 Javascript
js确认删除对话框适用于a标签及submit
Jul 10 Javascript
JavaScript通过使用onerror设置默认图像显示代替alt
Mar 01 Javascript
JavaScript数据操作_浅谈原始值和引用值的操作本质
Aug 23 Javascript
AngularJs  Using $location详解及示例代码
Sep 02 Javascript
详解如何在vue项目中引入elementUI组件
Feb 11 Javascript
微信小程序框架wepy之动态控制类名
Sep 14 Javascript
vue中的计算属性实例详解
Sep 19 Javascript
vue的keep-alive中使用EventBus的方法
Apr 23 Javascript
layui table 复选框跳页后再回来保持原来选中的状态示例
Oct 26 Javascript
JS实现漂亮的淡蓝色滑动门效果代码
Sep 23 #Javascript
jQuery Validate验证框架经典大全
Sep 23 #Javascript
Javascript实现的简单右键菜单类
Sep 23 #Javascript
js实现无限级树形导航列表效果代码
Sep 23 #Javascript
JS实现同一个网页布局滑动门和TAB选项卡实例
Sep 23 #Javascript
JS实现3D图片旋转展示效果代码
Sep 22 #Javascript
JS+CSS实现带小三角指引的滑动门效果
Sep 22 #Javascript
You might like
10个实用的PHP代码片段
2011/09/02 PHP
php实现memcache缓存示例讲解
2013/12/04 PHP
PHP5.4起内置web服务器使用方法
2016/08/09 PHP
动态表单验证的操作方法和TP框架里面的ajax表单验证
2017/07/19 PHP
详解PHP实现支付宝小程序用户授权的工具类
2018/12/25 PHP
Yii使用EasyWechat实现小程序获取用户的openID的方法
2020/04/29 PHP
jquery的index方法实现tab效果
2011/02/16 Javascript
jquery中的mouseleave和mouseout的区别 模仿下拉框效果
2012/02/07 Javascript
JavaScript设计模式之原型模式(Object.create与prototype)介绍
2014/12/28 Javascript
jQuery中复合属性选择器用法实例
2014/12/31 Javascript
JQUERY的AJAX请求缓存里的数据问题处理
2016/02/23 Javascript
手机浏览器 后退按钮强制刷新页面方法总结
2016/10/09 Javascript
webpack使用 babel-loader 转换 ES6代码示例
2017/08/21 Javascript
Angular4编程之表单响应功能示例
2017/12/13 Javascript
代码详解JS操作剪贴板
2018/02/11 Javascript
vue和better-scroll实现列表左右联动效果详解
2019/04/29 Javascript
新手快速入门JavaScript装饰者模式与AOP
2019/06/24 Javascript
vue 验证码界面实现点击后标灰并设置div按钮不可点击状态
2019/10/28 Javascript
jQuery Raty星级评分插件使用方法实例分析
2019/11/25 jQuery
vue项目中使用bpmn-自定义platter的示例代码
2020/05/11 Javascript
vue设置默认首页的操作
2020/08/12 Javascript
理解python多线程(python多线程简明教程)
2014/06/09 Python
Python深入学习之上下文管理器
2014/08/31 Python
Python爬虫包BeautifulSoup异常处理(二)
2018/06/17 Python
python中实现字符串翻转的方法
2018/07/11 Python
win10下python3.5.2和tensorflow安装环境搭建教程
2018/09/19 Python
Python使用itchat模块实现群聊转发,自动回复功能示例
2019/08/26 Python
Python爬虫爬取Bilibili弹幕过程解析
2019/10/10 Python
python安装第三方库如xlrd的方法
2020/10/31 Python
法学毕业生自荐信
2013/11/13 职场文书
司机岗位职责
2013/11/15 职场文书
竞选班长演讲稿
2013/12/30 职场文书
自我查摆剖析材料
2014/10/11 职场文书
高老头读书笔记
2015/06/30 职场文书
传单、海报早OUT了,另类传单营销方案送给你!
2019/07/15 职场文书
MySql子查询IN的执行和优化的实现
2021/08/02 MySQL