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 相关文章推荐
Stop SQL Server
Jun 21 Javascript
使用滤镜设置透明导致 IE 6/7/8/9 解析异常的解决方法
Apr 07 Javascript
javascript中方便增删改cookie的一个类
Oct 11 Javascript
JS模拟自动点击的简单实例
Aug 08 Javascript
JS 清除字符串数组中,重复元素的实现方法
May 24 Javascript
关于JavaScript数组你所不知道的3件事
Aug 24 Javascript
最好用的Bootstrap fileinput.js文件上传组件
Dec 12 Javascript
AngularJS的依赖注入实例分析(使用module和injector)
Jan 19 Javascript
Bootstrap缩略图与警告框学习使用
Feb 08 Javascript
ES6解构赋值的功能与用途实例分析
Oct 31 Javascript
js变量声明var使用与不使用的区别详解
Jan 21 Javascript
vue中用 async/await 来处理异步操作
Jul 18 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 SPL标准库的用法(遍历目录,查找固定条件的文件)
2013/06/18 PHP
PHP生成制作验证码的简单实例
2016/06/12 PHP
JavaScript 学习笔记(十六) js事件
2010/02/01 Javascript
使用JQuery快速实现Tab的AJAX动态载入(实例讲解)
2013/12/11 Javascript
jQuery事件绑定与解除绑定实现方法
2015/04/15 Javascript
详解JavaScript中常用的函数类型
2015/11/18 Javascript
JS提交form表单实例分析
2015/12/10 Javascript
自动完成的搜索框javascript实现
2016/02/26 Javascript
JS三级可折叠菜单实现方法
2016/02/29 Javascript
js实现多行文本框统计剩余字数功能
2017/03/28 Javascript
Angular5.1新功能分享
2017/12/21 Javascript
JavaScript实现新年倒计时效果
2018/11/17 Javascript
解决vue 子组件修改父组件传来的props值报错问题
2019/11/09 Javascript
Nodejs + Websocket 指定发送及群聊的实现
2020/01/09 NodeJs
TypeScript的安装、使用、自动编译的实现
2020/04/10 Javascript
vue实现拖拽进度条
2021/03/01 Vue.js
Python过滤函数filter()使用自定义函数过滤序列实例
2014/08/26 Python
python中的__slots__使用示例
2015/02/26 Python
Python使用Paramiko模块编写脚本进行远程服务器操作
2016/05/05 Python
python版微信跳一跳游戏辅助
2018/01/11 Python
Python使用win32 COM实现Excel的写入与保存功能示例
2018/05/03 Python
Python socket套接字实现C/S模式远程命令执行功能案例
2018/07/06 Python
python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换)
2019/04/01 Python
通过python实现windows桌面截图代码实例
2020/01/17 Python
通过python-pptx模块操作ppt文件的方法
2020/12/26 Python
英国Zoro工具:手动工具,电动工具和个人防护用品
2016/11/02 全球购物
MyBag中文网:英国著名的时尚包袋电商零售网站
2020/07/31 全球购物
长辈证婚人证婚词
2014/01/09 职场文书
中学生个人自我评价
2014/02/06 职场文书
毕业论文评语大全
2014/04/29 职场文书
党员领导干部承诺书
2014/05/28 职场文书
感情真挚的毕业生求职信
2014/07/19 职场文书
2015年幼儿园国庆节活动总结
2015/07/30 职场文书
体育教师研修感悟
2015/11/18 职场文书
如何在Mac上通过docker配置PHP开发环境
2021/05/29 PHP
jQuery实现广告显示和隐藏动画
2021/07/04 jQuery