直接拿来用的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 相关文章推荐
setAttribute 与 class冲突解决
Feb 17 Javascript
js有序数组的连接问题
Oct 01 Javascript
Mac/Windows下如何安装Node.js
Nov 22 Javascript
浅析jQuery1.8的几个小变化
Dec 10 Javascript
三分钟带你玩转jQuery.noConflict()
Feb 15 Javascript
详解Jquery EasyUI tree 的异步加载(遍历指定文件夹,根据文件夹内的文件生成tree)
Feb 11 Javascript
基于 Bootstrap Datetimepicker 联动
Aug 03 Javascript
JS实现的简单表单验证功能完整实例
Oct 14 Javascript
小程序getLocation需要在app.json中声明permission字段
Apr 04 Javascript
Vuex新手的理解与使用详解
May 31 Javascript
js实现简易拖拽的示例
Oct 26 Javascript
解决vue打包 npm run build-test突然不动了的问题
Nov 13 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
LotusPhp笔记之:Cookie组件的使用详解
2013/05/06 PHP
php中json_encode处理gbk与gb2312中文乱码问题的解决方法
2014/07/10 PHP
php字符串分割函数用法实例
2015/03/17 PHP
PHP实现通过get方式识别用户发送邮件的方法
2015/07/16 PHP
php简单实现多语言切换的方法
2016/05/09 PHP
Yii2实现UploadedFile上传文件示例
2017/02/15 PHP
解决 firefox 不支持 document.all的方法
2007/03/12 Javascript
jquery 插件学习(二)
2012/08/06 Javascript
引入autocomplete组件时JS报未结束字符串常量错误
2014/03/19 Javascript
JavaScript插件化开发教程 (一)
2015/01/27 Javascript
触屏中的JavaScript事件分析
2015/02/06 Javascript
利用JQuery写一个简单的异步分页插件
2016/03/07 Javascript
在js代码拼接dom对象到页面上去的模板总结(必看)
2017/02/14 Javascript
vue2.0设置proxyTable使用axios进行跨域请求的方法
2017/10/19 Javascript
原生JS与jQuery编写简单选项卡
2017/10/30 jQuery
vue2 mint-ui loadmore实现下拉刷新,上拉更多功能
2018/03/21 Javascript
Node.js log4js日志管理详解
2018/07/31 Javascript
Jquery的Ajax技术使用方法
2019/01/21 jQuery
你知道JavaScript Symbol类型怎么用吗
2020/01/08 Javascript
JS实现页面鼠标点击出现图片特效
2020/08/19 Javascript
[01:05:56]Liquid vs VP Supermajor决赛 BO 第二场 6.10
2018/07/04 DOTA
Java实现的执行python脚本工具类示例【使用jython.jar】
2018/03/29 Python
python3中zip()函数使用详解
2018/06/29 Python
对Python3 序列解包详解
2019/02/16 Python
Python字典取键、值对的方法步骤
2020/09/30 Python
Python之京东商品秒杀的实现示例
2021/01/06 Python
委托证明的格式
2014/01/10 职场文书
《傅雷家书》教学反思
2014/04/20 职场文书
女生节标语
2014/06/26 职场文书
教师节倡议书
2014/08/30 职场文书
2014社会治安综合治理工作总结
2014/12/04 职场文书
表扬信格式模板
2015/05/05 职场文书
我是特种兵观后感
2015/06/11 职场文书
公司环境卫生管理制度
2015/08/05 职场文书
学校中层领导培训心得体会
2016/01/11 职场文书
vue3如何优雅的实现移动端登录注册模块
2021/03/29 Vue.js