直接拿来用的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 不只是脚本
May 30 Javascript
Google Map API更新实现用户自定义标注坐标
Jul 29 Javascript
js实现连续英文字符自动换行兼容ie6 ie7和firefox
Sep 06 Javascript
JQuery Highcharts 动态生成图表的方法
Nov 15 Javascript
jquery中ajax函数执行顺序问题之如何设置同步
Feb 28 Javascript
JS获得选取checkbox整行数据的方法
Jan 28 Javascript
JS获取checkbox的个数简单实例
Aug 19 Javascript
bootstrap table动态加载数据示例代码
Mar 25 Javascript
JavaScript Canvas绘制圆形时钟效果
Aug 20 Javascript
解决vue打包后vendor.js文件过大问题
Jul 03 Javascript
vue登录注册实例详解
Sep 14 Javascript
vue+element树组件 实现树懒加载的过程详解
Oct 21 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
自己前几天写的无限分类类
2007/02/14 PHP
PHP日期时间函数的高级应用技巧
2009/05/16 PHP
phpMyAdmin 安装配置方法和问题解决
2009/06/08 PHP
thinkphp模板继承实例简述
2014/11/26 PHP
驱动事件的addEvent.js代码
2007/03/27 Javascript
js jquery做的图片连续滚动代码
2008/01/06 Javascript
JS控件的生命周期介绍
2012/10/22 Javascript
node.js中的fs.lstat方法使用说明
2014/12/16 Javascript
jQuery图片特效插件Revealing实现拉伸放大
2015/04/22 Javascript
javascript手风琴下拉菜单实现代码
2015/11/12 Javascript
javascript实现C语言经典程序题
2015/11/29 Javascript
Bootstrap每天必学之附加导航(Affix)插件
2016/04/25 Javascript
AngularJS使用ng-app自动加载bootstrap框架问题分析
2017/01/04 Javascript
js实现三级联动效果(简单易懂)
2017/03/27 Javascript
bootstrap table表格插件使用详解
2017/05/08 Javascript
对存在JavaScript隐式类型转换的四种情况的总结(必看篇)
2017/08/31 Javascript
9种使用Chrome Firefox 自带调试工具调试javascript技巧
2017/12/22 Javascript
微信小程序实现团购或秒杀批量倒计时
2020/11/01 Javascript
详解在React项目中安装并使用Less(用法总结)
2019/03/18 Javascript
微信小程序页面间跳转传参方式总结
2019/06/13 Javascript
Vuex中实现数据状态查询与更改
2019/11/08 Javascript
编写v-for循环的技巧汇总
2020/12/01 Javascript
[01:02:32]DOTA2-DPC中国联赛 正赛 iG vs PSG.LGD BO3 第二场 2月26日
2021/03/11 DOTA
深入解析Python中的urllib2模块
2015/11/13 Python
使用Python读写及压缩和解压缩文件的示例
2016/07/08 Python
浅谈python中真正关闭socket的方法
2018/12/18 Python
Python对wav文件的重采样实例
2020/02/25 Python
python 下载m3u8视频的示例代码
2020/11/11 Python
西班牙灯具网上商店:Lampara.es
2018/06/05 全球购物
e路東瀛(JAPANiCAN)香港:日本旅游、日本酒店和温泉旅馆预订
2018/11/21 全球购物
祖国在我心中演讲稿400字
2014/05/04 职场文书
办理房产过户的委托书
2014/09/14 职场文书
购房协议书范本(无房产证)
2014/10/07 职场文书
民主评议政风行风活动心得体会
2014/10/29 职场文书
2016年五一劳动节专题校园广播稿
2015/12/17 职场文书
Pytorch GPU内存占用很高,但是利用率很低如何解决
2021/06/01 Python