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 相关文章推荐
DOM Scripting中的图片切换[兼容Firefox]
Jun 12 Javascript
ExtJS4 Grid改变单元格背景颜色及Column render学习
Feb 06 Javascript
JavaScript实现自己的DOM选择器原理及代码
Mar 04 Javascript
JS实现的颜色实时渐变效果完整实例
Mar 25 Javascript
理解javascript模块化
Mar 28 Javascript
基于Bootstrap使用jQuery实现输入框组input-group的添加与删除
May 03 Javascript
React Native实现简单的登录功能(推荐)
Sep 19 Javascript
bootstrap与Jquery UI 按钮样式冲突的解决办法
Sep 23 Javascript
完美解决jQuery的hover事件在IE中不停闪动的问题
Feb 10 Javascript
原生js实现轮播图的示例代码
Feb 20 Javascript
vue 框架下自定义滚动条(easyscroll)实现方法
Aug 29 Javascript
三步实现ionic3点击退出app程序
Sep 17 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
Django中通过定时任务触发页面静态化的处理方式
2018/08/29 PHP
jquery 操作单选框,复选框,下拉列表实现代码
2009/10/27 Javascript
自制基于jQuery的智能提示插件一枚
2011/02/18 Javascript
jquery checkbox实现单选小例
2013/11/27 Javascript
jquery实现全选功能效果的实现代码
2016/05/05 Javascript
BootStrap的JS插件之轮播效果案例详解
2016/05/16 Javascript
javascript动画之模拟拖拽效果篇
2016/09/26 Javascript
详解Javascript中的原型OOP
2016/10/12 Javascript
jQuery.parseHTML() 函数详解
2017/01/09 Javascript
Angular.JS中的指令引用template与指令当做属性详解
2017/03/30 Javascript
Vue+axios 实现http拦截及路由拦截实例
2017/04/25 Javascript
详解基于Angular4+ server render(服务端渲染)开发教程
2017/08/28 Javascript
vue 登录滑动验证实现代码
2018/08/24 Javascript
利用vue.js把静态json绑定bootstrap的table方法
2018/08/28 Javascript
VUE搭建手机商城心得和遇到的坑
2019/02/21 Javascript
iview tabs 顶部导航栏和模块切换栏的示例代码
2019/03/04 Javascript
浅谈Vue3.0新版API之composition-api入坑指南
2020/04/30 Javascript
javascript实现拼图游戏
2021/01/29 Javascript
python在Windows下安装setuptools(easy_install工具)步骤详解
2016/07/01 Python
Python编程实现双链表,栈,队列及二叉树的方法示例
2017/11/01 Python
浅谈numpy数组中冒号和负号的含义
2018/04/18 Python
Python selenium根据class定位页面元素的方法
2019/02/26 Python
使用Python实现毫秒级抢单功能
2019/06/06 Python
浅谈Tensorflow加载Vgg预训练模型的几个注意事项
2020/05/26 Python
PyQt5.6+pycharm配置以及pyinstaller生成exe(小白教程)
2020/06/02 Python
利用Python实现自动扫雷小脚本
2020/12/17 Python
HTML5 CSS3实现一个精美VCD包装盒个性幻灯片案例
2014/06/16 HTML / CSS
bareMinerals官网:矿物质化妆品和护肤品
2018/02/04 全球购物
Pharmacy Online中文直邮网站:澳洲大型药房
2020/06/27 全球购物
什么时候需要进行强制类型转换
2016/09/03 面试题
电子商务专业毕业生工作推荐信
2013/11/17 职场文书
上班迟到检讨书300字
2014/10/18 职场文书
奖学金个人总结
2015/03/04 职场文书
获奖感言一句话
2015/07/31 职场文书
微软Win11什么功能最惊艳? Windows11新功能特性汇总
2021/11/21 数码科技
mysql通过group by分组取最大时间对应数据的两种有效方法
2022/09/23 MySQL