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 相关文章推荐
IE8 引入跨站数据获取功能说明
Jul 22 Javascript
javascript动态改变img的src属性图片不显示的解决方法
Oct 20 Javascript
利用jQuery的deferred对象实现异步按顺序加载JS文件
Mar 17 Javascript
批量下载对路网图片并生成html的实现方法
Jun 07 Javascript
js获取时间函数及扩展函数的方法
Oct 30 Javascript
webix+springmvc session超时跳转登录页面
Oct 30 Javascript
用JavaScript和jQuery实现瀑布流
Mar 19 Javascript
Angular2的管道Pipe的使用方法
Nov 07 Javascript
详解VUE-地区选择器(V-Distpicker)组件使用心得
May 07 Javascript
vue实现图片上传预览功能
Dec 23 Javascript
React Hooks 实现和由来以及解决的问题详解
Jan 17 Javascript
JavaScript 异步时序问题
Nov 20 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设置session(过期、失效、有效期)
2015/11/12 PHP
php阿拉伯数字转中文人民币大写
2015/12/21 PHP
PHP实现webshell扫描文件木马的方法
2017/07/31 PHP
laravel 5.5 关闭token的3种实现方式
2019/10/24 PHP
ASP.NET jQuery 实例17 通过使用jQuery validation插件校验ListBox
2012/02/03 Javascript
通过jquery还原含有rowspan、colspan的table的实现方法
2012/02/10 Javascript
jQuery中eq()方法用法实例
2015/01/05 Javascript
限制上传文件大小和格式的jQuery插件实例
2015/01/24 Javascript
JavaScript中使用自然对数ln的方法
2015/06/14 Javascript
ECHO.js 纯javascript轻量级延迟加载的实例代码
2016/05/24 Javascript
Bootstrap Navbar Component实现响应式导航
2016/10/08 Javascript
详解Javascript中的原型OOP
2016/10/12 Javascript
JavaScript 限制文本框不可输入英文单双引号的方法
2016/12/20 Javascript
基于Bootstrap的Java开发问题汇总(Spring MVC)
2017/01/15 Javascript
JavaScript自定义分页样式
2017/01/17 Javascript
Ajax异步获取html数据中包含js方法无效的解决方法
2017/02/20 Javascript
原生js更改css样式的两种方式
2017/03/15 Javascript
JS变量及其作用域
2017/03/29 Javascript
微信扫码支付零云插件版实例详解
2017/04/26 Javascript
node.js中grunt和gulp的区别详解
2017/07/17 Javascript
原生nodejs使用websocket代码分享
2018/04/07 NodeJs
详解在vue-cli中使用graphql即vue-apollo的用法
2018/09/08 Javascript
JS判断两个数组或对象是否相同的方法示例
2019/02/28 Javascript
Vue清除定时器setInterval优化方案分享
2020/07/21 Javascript
[03:40]2014DOTA2国际邀请赛 B神专访:躲箭真的很难
2014/07/13 DOTA
[01:06:42]VP vs NewBee Supermajor 胜者组 BO3 第二场 6.5
2018/06/06 DOTA
Python中tell()方法的使用详解
2015/05/24 Python
Python编程中对super函数的正确理解和用法解析
2016/07/02 Python
解决Tensorflow安装成功,但在导入时报错的问题
2018/06/13 Python
在PyCharm下使用 ipython 交互式编程的方法
2019/01/17 Python
Python3 串口接收与发送16进制数据包的实例
2019/06/12 Python
Python获取命令实时输出-原样彩色输出并返回输出结果的示例
2019/07/11 Python
法学专业应届生求职信
2013/10/16 职场文书
迟到早退检讨书
2014/02/10 职场文书
优秀的2014年两会精神解读
2014/03/17 职场文书
建材投资建议书
2014/05/16 职场文书