当前位置: 首页 > 科技观察

每个程序员都知道的35个jQuery技巧

时间:2023-03-17 13:16:30 科技观察

1.禁止右键单击$(document)。;});2。隐藏搜索文本框文本Hidewhenclickedinthesearchfield,thevalue.(examplecanbebefoundbelowinthecommentfields)$(document).ready(function(){$("input.text1").val("Enteryoursearchtextthere");textFill($('input.text1'));});functiontextFill(input){//inputfocustextfunctionvaroriginalvalue=input.val();input.focus(function(){if($.trim(input.val())==originalvalue){input.val('');}});input.blur(function(){if($.trim(input.val())==''){input.val(originalvalue);}});}3.打开链接在新窗口中XHTML1.0Strict不允许在代码中使用此属性,因此请保持代码有效。$(document).ready(function(){//Example1:Everylinkwillopeninanewwindow$('a[href^="http://"]').attr("target","_blank");//Example2:Linkswiththerel="external"属性只会打开一个newwindow$('a[@rel$='external']').click(function(){this.target="_blank";});});//howtouseopenlink4.检测浏览器注意:在jQuery1版本中.4、$.support替换$.browser变量$(document).ready(function(){//TargetFirefox2andaboveif($.browser.mozilla&&$.browser.version>="1.8"){//dosomething}//TargetSafariif($.browser.safari){//dosomething}//TargetChromeif($.browser.chrome){//dosomething}//TargetCaminoif($.browser.camino){//dosomething}//TargetOperaif($.browser.opera){//dosomething}//TargetIE6andbelowif($.browser.msie&&$.browser.version<=6){//dosomething}//TargetanythingaboveIE6if($.browser.msie&&$.browser.version>6){//做一点事}});5.预加载图片这段代码将阻止加载图片,如果您的网站有很多图片,这会很有用。$(document).ready(function(){jQuery.preloadImages=function(){for(vari=0;i").attr("src",参数[i]);}}//如何使用$.preloadImages("image1.jpg");});6.页面样式切换$(document).ready(function(){$("a.Styleswitcher").click(function(){//swicththeLINKRELattributewiththevalueinAREAttribute$('link[rel=stylesheet]').attr('href',$(this).attr('rel'));});//howtouse//placethisinyourheader//thelinks默认主题红色主题蓝色主题});7.列的高度相同如果使用两个CSS列,这样两列的高度可以相同$(document).ready(function(){functionequalHeight(group){tallest=0;group.each(function(){thisHeight=$(this).height();if(thisHeight>tallest){tallest=thisHeight;}});group.height(tallest);}//howtouse$(document).ready(function(){equalHeight($(".left"));equalHeight($(".right"));});});8.动态控制页面字体大用户可以修改页面字体大$(document).ready(function(){//Resetthefontsize(backtodefault)varoriginalFontSize=$('html').css('font-size');$(".resetFont").click(function(){$('html').css('font-size',originalFontSize);});//增加字体大小(biggerfont0$(".increaseFont").click(function(){varcurrentFontSize=$('html').css('字体大小');varcurrentFontSizeNum=parseFloat(currentFontSize,10);varnewFontSize=currentFontSizeNum*1.2;$('html').css('字体大小',newFontSize);returnfalse;});//减少字体大小(smallerfont)$(".decreaseFont").click(function(){varcurrentFontSize=$('html').css('font-size');varcurrentFontSizeNum=parseFloat(currentFontSize,10);varnewFontSize=currentFontSizeNum*0.8;$('html').css('font-size',newFontSize);returnfalse;});});9.返回页面顶部功能为了平稳(动画)回到顶部(或任何位置)。$(document).ready(function(){$('a[href*=#]').click(function(){if(location.pathname.replace(/^\//,'')==this.pathname.replace(/^\//,'')&&location.hostname==this.hostname){var$target=$(this.hash);$target=$target.length&&$target||$('[name='+this.hash.slice(1)+']');if($target.length){vartargetOffset=$target.offset().top;$('html,body').animate({scrollTop:targetOffset},900);returnfalse;}}});//howtouse//placethiswhereyouwanttoscrollto//thelinkgototop});10.获得鼠标指针XY值想知道你的鼠标光标在哪里?$(document).ready(function(){$().mousemove(function(e){//displaythexandyaxisvaluesinsidethedivwiththeidXY$('#XY').html("XAxis:"+e.pageX+"|YAxis"+e.pageY);});//如何使用

});#p#11。返回顶部按钮可以使用animate和scrollTop实现返回顶部的动画,无需使用其他插件//Backtotop$('a.top')。点击(function(){$(document.body).animate({scrollTop:0},800);returnfalse;});返回顶部ChangescrollTop的值可以调整返回到顶部的距离,animate的第二个参数是执行返回动作所需的时间(单位:毫秒)。12.预加载图片如果你的页面使用了很多不可见的图片(比如:悬停显示),你可能需要预加载它们:$.preloadImages=function(){for(vari=0;i').attr('src',arguments[i]);}};$.preloadImages('img/hover1.png','img/hover2.png');13.检查是否图像已加载。有时您需要确保图像已加载,以便您可以执行后续操作:$('img').load(function(){console.log('imageloadsuccessful');});你可以把img替换成另一个ID或class来检查是否加载了指定的图像。14.自动修复损坏的图片如果您碰巧在您的站点上发现损坏的图片链接,您可以用不容易替换的图片替换它们。添加这个简单的代码将为您省去很多麻烦:$('img').on('error',function(){$(this).prop('src','img/broken.png');});即使您的网站没有损坏的图片链接,添加此代码也没有什么坏处。15.鼠标悬停(hover)切换类属性如果想改变用户悬停在可点击元素上时的效果,下面的代码可以添加鼠标悬停在元素上时的类属性。当用户离开鼠标时,class属性自动取消:$('.btn').hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('悬停');});您只需要添加必要的CSS代码。如果你想要更简洁的代码,可以使用toggleClass方法:$('.btn').hover(function(){$(this).toggleClass('hover');});注意:直接使用CSS来实现这个Effects可能是更好的解决方案,但是你还是需要知道方法。16.禁用输入字段有时您可能需要禁用表单或输入字段的提交按钮,直到用户执行某些操作(例如,选中“阅读条款”复选框)。您可以添加disabled属性,直到您想要启用它:$('input[type="submit"]').prop('disabled',true);你所要做的就是执行removeAttr方法并将属性作为参数传入:$('input[type="submit"]').removeAttr('disabled');17.防止链接加载有时你不想链接到某个页面或重新加载它,你可能想让它做些别的事情或触发一些其他的脚本,你可以这样做:$('a.no-link').click(函数(e){e.preventDefault();});18.切换淡入淡出/滑动淡入淡出和滑动是我们在jQuery中经常使用的一种动画效果,它们可以使元素显示效果更好。但是如果你想在元素显示时使用第一个效果,在元素消失时使用第二个效果,你可以这样做://Fade$('.btn').click(function(){$('.element').fadeToggle('slow');});//Toggle$('.btn').click(function(){$('.element').slideToggle('slow');});19.简单的手风琴效果这是实现手风琴效果的快速简便的方法://Closeallpanels$('#accordion').find('.content').hide();//Accordion$('#accordion')。查找('.accordion-header').click(function(){varnext=$(this).next();next.slideToggle('fast');$('.content').not(next).slideUp('快');返回假;});20.使两个DIV高度相同有时您需要使两个div具有相同高度,无论它们里面有多少内容。您可以使用以下代码片段:var$columns=$('.column');varheight=0;$columns.each(function(){if($(this).height()>height){height=$(this).height();}});$columns.height(height);此代码循环遍历一组元素并将它们的高度设置为元素中最高的。#p#21。验证元素是否为空Thiswillallowyoutocheckifanelementisempty.$(document).ready(function(){if($('#id').html()){//dosomething}});22.替换元素$(document).ready(function(){$('#id').replaceWith('
我已经被替换
');});23.jQuery延迟加载函数$(document).ready(function(){window.setTimeout(function(){//dosomething},1000);});24.去掉单词函数$(document).ready(function(){varel=$('#id');el.html(el.html().replace(/word/ig,""));});25.验证jquery对象集合中是否存在该元素$(document).ready(function(){if($('#id').length){//dosomething}});26.使整个DIV可点击("href");returnfalse;});//howtouse
home
});27.ID与Class的转换改变Window大小时,ID与Class的转换$(document).ready(function(){functioncheckWindowSize(){if($(window).width()>1200){$('身体').addClass('large');}else{$('body').removeClass('large');}}$(window).resize(checkWindowSize);});28.克隆对象$(document).ready(function(){varcloned=$('#id').clone();//howtouse
});29.让元素在屏幕中间$(document).ready(function(){jQuery.fn.center=function(){this.css("position","absolute");this.css("top",($(window).height()-this.height())/2+$(window).scrollTop()+"px");this.css("left",($(window).width()-this.width())/2+$(window).scrollLeft()+"px");returnthis;}$("#id").center();});30.编写自己的选择器$(document).ready(function(){$.extend($.expr[':'],{moreThen1000px:function(a){return$(a)??.width()>1000;}});$('.box:moreThen1000px').click(function(){//creatingasimplejsalertboxalert('Theelementthatyouhaveclickedisover1000pixelswide');});});31.计算元素的数量$(document).ready(function(){$("p").size();});32。使用您自己的Bullets$(文档)。ready(function(){$("ul").addClass("替换");$("ul>li").prepend("?");//howtouseul.Replaced{list-style:none;}});33.引用Google主机上的Jquery类库//Example1google.load("jquery","1.2.6");google.setOnLoadCallback(function(){//dosomething});//Example2:(thebestandfastestway)34.禁用Jquery(animation)effect$(document).ready(function(){jQuery.fx.off=true;});35.与其他Javascript库的冲突解决$(document).ready(function(){var$jq=jQuery.noConflict();$jq('#id').show();});