在过去的几年中,jQuery一直是使用最为普遍的JavaScript脚本库。今天咱们将为各位Web开发者提供10个最实用的jQuery代码片断,有须要的开发者能够保存起来。html
当涉及到CSS设计时,对开发者和设计者而言Internet Explorer一直是个问题。尽管IE6的黑暗时代已通过去,IE也愈来愈不流行,它始终是一个可以容易检测的好东西。固然了,下面的代码也能用于检测别的浏览器。浏览器
$(document).ready(function() { if (navigator.userAgent.match(/msie/i) ){ alert('I am an old fashioned Internet Explorer'); } });
这是一个最普遍使用的jQuery效果:对一个连接点击下会平稳地将页面移动到顶部。这里没什么新的内容,可是每一个开发者必需要会偶尔编写一下相似函数app
$("a[href='#top']").click(function() { $("html, body").animate({ scrollTop: 0 }, "slow"); return false; });
很是有用的代码片断,它容许一个元素固定在顶部。对导航按钮、工具栏或重要信息框是超级有用的。函数
$(function(){ var $win = $(window); var $nav = $('.mytoolbar'); var navTop = $('.mytoolbar').length && $('.mytoolbar').offset().top; var isFixed=0; processScroll() $win.on('scroll', processScroll) function processScroll() { var i, scrollTop = $win.scrollTop(); if (scrollTop >= navTop && !isFixed) { isFixed = 1 $nav.addClass('subnav-fixed') } else if (scrollTop <= navTop && isFixed) { isFixed = 0 $nav.removeClass('subnav-fixed') } }
jQuery使得用另一个东西取代html标志很简单。能够利用的余地无穷无尽。工具
$('li').replaceWith(function(){ return $("<div />").append($(this).contents()); });
如今移动设备比过期的电脑更广泛,可以方便去检测一个更小的视窗宽度会颇有帮助。幸运的是,用jQuery来作超级简单。this
var responsive_viewport = $(window).width(); /* if is below 481px */ if (responsive_viewport < 481) { alert('Viewport is smaller than 481px.'); } /* end smallest screen */
若是你的站点比较大并且已经在线运行了好多年,你或多或少会遇到界面上某个地方有损坏的图片。这个有用的函数可以帮助检测损坏图片并用你中意的图片替换它,并会将此问题通知给访客。spa
$('img').error(function(){ $(this).attr('src', 'img/broken.png'); });
使用jQuery能够很容易去根据你的要求去检测复制、粘贴和剪切的操做。设计
$("#textA").bind('copy', function() { $('span').text('copy behaviour detected!') }); $("#textA").bind('paste', function() { $('span').text('paste behaviour detected!') }); $("#textA").bind('cut', function() { $('span').text('cut behaviour detected!') });
当连接到外部站点时,你可能使用target=”blank”的属性去在新界面中打开站点。问题在于target=”blank”属性并非W3C有效的属性。让咱们用jQuery来补救:下面这段代码将会检测是否连接是外链,若是是,会自动添加一个target=”blank”属性。code
var root = location.protocol + '//' + location.host; $('a').not(':contains(root)').click(function(){ this.target = "_blank"; });
另外一个“经典的”代码,它要放到你的工具箱里,由于你会不时地要实现它。htm
$(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 }); });
在不少表格领域都不须要空格键,例如,电子邮件,用户名,密码等等等。这里是一个简单的技巧能够用于在选定输入中禁止空格键。
$('input.nospace').keydown(function(e) { if (e.keyCode == 32) { return false; } });