18个非常棒的jQuery代码片段


Posted in Javascript onNovember 02, 2015

1、jQuery实现的内链接平滑滚动
不需要使用太复杂的插件,只要使用下载这段代码即可实现基于内部链接的平滑滚动

$('a[href^="#"]').bind('click.smoothscroll',function (e) {
e.preventDefault();
 
var anchor = this.hash,
$target = $(target);
 
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 500, 'swing', function () {
window.location.hash = anchor;
});
 
});

2、使用jQuery获取所有节点

var $element = $('#gbtags');
 var $nodes = $element.contents();
 $nodes.each(function() {
  if(this.nodeType === 3 && $.trim($(this).text())) {
  $(this).wrap('');
 }
});

3、限制选择框选择个数

$("#categories option").click(function(e){
 if ($(this).parent().val().length < 2) {
  $(this).removeAttr("selected");
 }
});

4、jQuery使用通配符来删除class

var _c = 'your-icon-class'
 
$('.currency').removeClass (function (index, css) {
 return (css.match (/\bicon-\S+/g) || []).join(' ');
}).addClass('icon-'+_c);

5、切换启用和禁用

/* HTML
|
|
<input type="text" value="欢迎访问www.admin10000.com" /><input type="button" value="禁用按钮" />
|
|
*/
 
// Plugin
(function ($) {
 $.fn.toggleDisabled = function () {
  return this.each(function () {
   var $this = $(this);
   if ($this.attr('disabled')) $this.removeAttr('disabled');
   else $this.attr('disabled', 'disabled');
  });
 };
})(jQuery);
 
// TEST
$(function () {
 $('input:button').click(function () {
  $('input:text').toggleDisabled();
 });
});

6、平滑滚动返回顶端

<h1 id="anchor">admin10000.com</h1>
<a class="topLink" href="#anchor">返回顶端</a>
 
$(document).ready(function () {
 
 $("a.topLink").click(function () {
  $("html, body").animate({
   scrollTop: $($(this).attr("href")).offset().top + "px"
  }, {
   duration: 500,
   easing: "swing"
  });
  return false;
 });
 
});

7、使用jQuery和Google Analytics来跟踪表单

var array1 = [];
$(document).ready(function () {
 $('input').change(function () {
  var formbox = $(this).attr('id');
  array1.push(formbox);
  console.log("you filled out box " + array1);
 });
 $('#submit').click(function () {
  console.log('tracked ' + array1);
  //alert('this is the order of boxes you filled out: ' + array1);
  _gaq.push(['_trackEvent', 'Form', 'completed', '"' + array1 + '"']);
 });
});

8、超简单的密码强度提示

$('#pass').keyup(function (e) {
 var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$", "g");
 var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
 var enoughRegex = new RegExp("(?=.{6,}).*", "g");
 if (false == enoughRegex.test($(this).val())) {
  $('#passstrength').html('More Characters');
 } else if (strongRegex.test($(this).val())) {
  $('#passstrength').className = 'ok';
  $('#passstrength').html('Strong!');
 } else if (mediumRegex.test($(this).val())) {
  $('#passstrength').className = 'alert';
  $('#passstrength').html('Medium!');
 } else {
  $('#passstrength').className = 'error';
  $('#passstrength').html('Weak!');
 }
 return true;
});

9、jQuery生成一个自动停靠页尾效果

// Window load event used just in case window height is dependant upon images
$(window).bind("load", function () {
 var footerHeight = 0,
  footerTop = 0,
  $footer = $("#footer");
 positionFooter();
 
 function positionFooter() {
  footerHeight = $footer.height();
  footerTop = ($(window).scrollTop() + $(window).height() - footerHeight) + "px";
  /* DEBUGGING
console.log("Document height: ", $(document.body).height());
console.log("Window height: ", $(window).height());
console.log("Window scroll: ", $(window).scrollTop());
console.log("Footer height: ", footerHeight);
console.log("Footer top: ", footerTop);
*/
  if (($(document.body).height() + footerHeight) < $(window).height()) {
   $footer.css({
    position: "absolute"
   }).stop().animate({
    top: footerTop
   });
  } else {
   $footer.css({
    position: "static"
   });
  }
 }
 
 $(window)
  .scroll(positionFooter)
  .resize(positionFooter);
});

10、预防对表单进行多次提交

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

11、图像等比例缩放

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

12、鼠标滑动时的渐入和渐出

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

13、制作等高的列

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

14、图片预加载

(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");

15、获取 URL 中传递的参数

$.urlParam = function(name){
 var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
 if (!results) { return 0; }
 return results[1] || 0;
}

16、禁用表单的回车键提交

$("#form").keypress(function(e) {
 if (e.which == 13) {
 return false;
 }
});

17、让整个DIV可以被点击

<div class = "myBox" > 
 < a href = "https://3water.com" > 3water.com < /a>
</div > 
 
$(".myBox").click(function(){
 window.location=$(this).find("a").attr("href");
 return false;
});

18、在新窗口打开链接 (target=”blank”)   

$('a[@rel$='external']').click(function(){
   this.target = "_blank";
});

 大家可以结合之前小编整理的文章进行学习,把实用的jQuery代码片段进行汇总,以便日后学习使用。

Javascript 相关文章推荐
javascript 对象定义方法 简单易学
Mar 22 Javascript
JQuery使用index方法获取Jquery对象数组下标的方法
May 18 Javascript
WordPress中鼠标悬停显示和隐藏评论及引用按钮的实现
Jan 12 Javascript
JavaScript Date对象详解
Mar 01 Javascript
Bootstrap学习笔记之css组件(3)
Jun 07 Javascript
Javascript中常用的检测方法小结
Oct 08 Javascript
JS 学习总结之正则表达式的懒惰性和贪婪性
Jul 03 Javascript
Angular2 自定义validators的实现方法
Jul 05 Javascript
react实现一个优雅的图片占位模块组件详解
Oct 30 Javascript
vue轮播组件实现$children和$parent 附带好用的gif录制工具
Sep 26 Javascript
JS实现小星星特效
Dec 24 Javascript
JS数据类型判断的几种常用方法
Jul 07 Javascript
js实现文件上传表单域美化特效
Nov 02 #Javascript
非常实用的12个jquery代码片段
Nov 02 #Javascript
jQuery+CSS3折叠卡片式下拉列表框实现效果
Nov 02 #Javascript
jquery 表单验证之通过 class验证表单不为空
Nov 02 #Javascript
纯javascript移动优先的幻灯片效果
Nov 02 #Javascript
JS实现点击按钮获取页面高度的方法
Nov 02 #Javascript
基于jQuery实现自动轮播旋转木马特效
Nov 02 #Javascript
You might like
PHP 字符截取 解决中文的截取问题,不用mb系列
2009/09/29 PHP
PHP ajax 异步执行不等待执行结果的处理方法
2015/05/27 PHP
详解php设置session(过期、失效、有效期)
2015/11/12 PHP
PHP使用PDO实现mysql防注入功能详解
2019/12/20 PHP
php + ajax 实现的写入数据库操作简单示例
2020/05/16 PHP
JavaScript脚本性能的优化方法
2007/02/02 Javascript
Js中获取frames中的元素示例代码
2013/07/30 Javascript
从零学jquery之如何使用回调函数
2014/05/16 Javascript
JavaScript实现的链表数据结构实例
2015/04/02 Javascript
分享自己用JS做的扫雷小游戏
2016/02/17 Javascript
基于JavaScript实现类似于百度学术高级检索功能
2016/03/02 Javascript
微信小程序教程之本地图片上传(leancloud)实例详解
2016/11/16 Javascript
详解nodejs微信公众号开发——3.封装消息响应模块
2017/04/10 NodeJs
从零开始学习Node.js系列教程之SQLite3和MongoDB用法分析
2017/04/13 Javascript
JS实现点击下拉菜单把选择的内容同步到input输入框内的实例
2018/01/23 Javascript
Vue监听数据渲染DOM完以后执行某个函数详解
2018/09/11 Javascript
JS实现网页端猜数字小游戏
2020/03/06 Javascript
python赋值操作方法分享
2013/03/23 Python
Python 编码处理-str与Unicode的区别
2016/09/06 Python
Python外星人入侵游戏编程完整版
2020/03/30 Python
Python使用正则表达式获取网页中所需要的信息
2018/01/29 Python
Python字符串和正则表达式中的反斜杠('\')问题详解
2019/09/03 Python
Jupyter Notebook安装及使用方法解析
2020/11/12 Python
改变生活的男士内衣:SAXX Underwear
2019/08/28 全球购物
伦敦最受欢迎的蛋糕店:Konditor & Cook
2019/11/01 全球购物
20年同学聚会感言
2014/02/03 职场文书
体育教师个人的自我评价
2014/02/16 职场文书
创业者迈进成功第一步:如何写创业计划书?
2014/03/22 职场文书
五水共治捐款倡议书
2014/05/14 职场文书
新教师岗前培训方案
2014/06/05 职场文书
某集团股份有限公司委托书样本
2014/09/24 职场文书
市场部岗位职责范本
2015/04/15 职场文书
毕业感言怎么写
2015/07/31 职场文书
2016年小学“我们的节日·中秋节”活动总结
2016/04/05 职场文书
《天使的翅膀》读后感3篇
2019/12/20 职场文书
python字典进行运算原理及实例分享
2021/08/02 Python