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 入门基础知识 想学习js的朋友可以参考下
Dec 26 Javascript
让textarea自动调整大小的js代码
Apr 12 Javascript
JS判断网页广告是否被浏览器拦截过滤的代码
Apr 05 Javascript
javascript 中的 delete及delete运算符
Nov 15 Javascript
跟我学习javascript的浮点数精度
Nov 16 Javascript
详解js中构造流程图的核心技术JsPlumb(2)
Dec 08 Javascript
Bootstrap简单表单显示学习笔记
Nov 15 Javascript
js时间戳转yyyy-MM-dd HH-mm-ss工具类详解
Apr 30 Javascript
微信小程序单选radio及多选checkbox按钮用法示例
Apr 30 Javascript
详解vue 动态加载并注册组件且通过 render动态创建该组件
May 30 Javascript
vue filter 完美时间日期格式的代码
Aug 14 Javascript
JS 数组基本用法入门示例解析
Jan 16 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 快速生成 Flash 动画的方法
2007/03/06 PHP
php.ini-dist 和 php.ini-recommended 的区别介绍(方便开发与安全的朋友)
2012/07/01 PHP
PHP与MongoDB简介|安全|M+PHP应用实例详解
2013/06/17 PHP
php实现curl模拟ftp上传的方法
2015/07/29 PHP
详解PHP归并排序的实现
2016/10/18 PHP
Symfony2创建基于域名的路由相关示例
2016/11/14 PHP
ThinkPHP框架表单验证操作方法
2017/07/19 PHP
解决laravel 表单提交-POST 异常的问题
2019/10/15 PHP
列表内容的选择
2006/06/30 Javascript
JQuery实现倒计时按钮的实现代码
2012/03/23 Javascript
Java 正则表达式学习总结和一些小例子
2012/09/13 Javascript
Extjs单独定义各组件的实例代码
2013/06/25 Javascript
JQuery设置获取下拉菜单某个选项的值(比较全)
2014/08/05 Javascript
jQuery中:lt选择器用法实例
2014/12/29 Javascript
你真的了解BOM中的history对象吗
2017/02/13 Javascript
Angular2 路由问题修复详解
2017/03/01 Javascript
微信小程序 连续旋转动画(this.animation.rotate)详解
2017/04/07 Javascript
对angular 监控数据模型变化的事件方法$watch详解
2018/10/09 Javascript
详解js动态获取浏览器或页面等容器的宽高
2019/03/13 Javascript
深入分析jQuery.one() 函数
2020/06/03 jQuery
详解Vue数据驱动原理
2020/11/17 Javascript
Python操作sqlite3快速、安全插入数据(防注入)的实例
2014/04/26 Python
pytorch训练imagenet分类的方法
2018/07/27 Python
python实现简单的单变量线性回归方法
2018/11/08 Python
python判断自身是否正在运行的方法
2019/08/08 Python
Pytorch实现神经网络的分类方式
2020/01/08 Python
对Tensorflow中Device实例的生成和管理详解
2020/02/04 Python
使用python接受tgam的脑波数据实例
2020/04/09 Python
TensorFlow固化模型的实现操作
2020/05/26 Python
python怎么判断素数
2020/07/01 Python
python 实现表情识别
2020/11/21 Python
HTML5中的Web Notification桌面通知功能的实现方法
2019/07/29 HTML / CSS
中国一家综合的外贸B2C电子商务网站:DealeXtreme(DX)
2020/03/10 全球购物
金融专业应届生求职信
2013/11/02 职场文书
计算机售后服务承诺书
2014/05/30 职场文书
JS 4个超级实用的小技巧 提升开发效率
2021/10/05 Javascript