直接拿来用的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+dom树型菜单类,希望朋友们一起进步
May 03 Javascript
JavaScript iframe的相互操作浅析
Oct 14 Javascript
caller和callee的区别介绍及演示结果
Mar 10 Javascript
关于js数组去重的问题小结
Jan 24 Javascript
用jquery修复在iframe下的页面锚点失效问题
Aug 22 Javascript
Javascript实现Web颜色值转换
Feb 05 Javascript
用瀑布流的方式在网页上插入图片的简单实现方法
Sep 23 Javascript
javascript验证香港身份证的格式或真实性
Feb 07 Javascript
Egg.js 中 AJax 上传文件获取参数的方法
Oct 10 Javascript
浅析vue-router原理
Oct 19 Javascript
微信小程序用户授权弹窗 拒绝时引导用户重新授权实现
Jul 29 Javascript
Vue数字输入框组件示例代码详解
Jan 15 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
无线电波是什么?它是怎样传输的?
2021/03/01 无线电
人脸识别测颜值、测脸龄、测相似度微信接口
2016/04/07 PHP
通过PHP实现用户注册后邮箱验证激活
2020/11/10 PHP
JQuery的一些小应用收集
2010/03/27 Javascript
JS表的模拟方法
2015/02/05 Javascript
超实用的JavaScript代码段 附使用方法
2016/05/22 Javascript
js删除局部变量的实现方法
2016/06/25 Javascript
Nodejs中 npm常用命令详解
2016/07/04 NodeJs
vue.js实现表格合并示例代码
2016/11/30 Javascript
Angularjs单选改为多选的开发过程及问题解析
2017/02/17 Javascript
基于vue2.0+vuex+localStorage开发的本地记事本示例
2017/02/28 Javascript
Vue.js中的组件系统
2019/05/30 Javascript
详解vue+axios给开发环境和生产环境配置不同的接口地址
2019/08/16 Javascript
vue视频播放插件vue-video-player的具体使用方法
2019/11/08 Javascript
微信小程序实现按字母排列选择城市功能
2019/11/25 Javascript
vue组件创建的三种方式小结
2020/02/03 Javascript
jQuery+ThinkPHP实现图片上传
2020/07/23 jQuery
[06:24]DOTA2亚洲邀请赛小组赛第三日 TOP10精彩集锦
2015/02/01 DOTA
一些Centos Python 生产环境的部署命令(推荐)
2018/05/07 Python
python 对给定可迭代集合统计出现频率,并排序的方法
2018/10/18 Python
Python最小二乘法矩阵
2019/01/02 Python
python协程之动态添加任务的方法
2019/02/19 Python
selenium跳过webdriver检测并模拟登录淘宝
2019/06/12 Python
OpenCV 模板匹配
2019/07/10 Python
Pandas0.25来了千万别错过这10大好用的新功能
2019/08/07 Python
Python中使用aiohttp模拟服务器出现错误问题及解决方法
2020/10/31 Python
css3中单位px,em,rem,vh,vw,vmin,vmax的区别及浏览器支持情况
2016/12/06 HTML / CSS
分解成质因数(如435234=251*17*17*3*2,据说是华为笔试题)
2014/07/16 面试题
大学毕业感言50字
2014/02/07 职场文书
满月酒主持词
2014/03/27 职场文书
离婚协议书怎样才有法律效力
2014/10/10 职场文书
司法局群众路线教育实践活动整改措施思想汇报
2014/10/13 职场文书
困难补助申请报告
2015/05/19 职场文书
生产车间管理制度
2015/08/04 职场文书
Golang的继承模拟实例
2021/06/30 Golang
VMware虚拟机安装 Windows Server 2022的详细图文教程
2022/09/23 Servers