26 个 jQuery使用技巧

本文提供26个实用的jQuery技巧,涵盖从基本操作到高级应用的各种场景,包括禁用右键点击、预加载图片、平滑滚动等功能,帮助开发者提高网页交互效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The use of the jQuery library is growing and growing(just released jQuery 1.4), more and more people are using this useful javascript library. This means that more and more useful jQuery tips, tricks and solutions are coming available. That’s why i created a small list of 26 cool and useful jQuery tips, tricks and solutions.



1. 禁用右键点击 (Disable right-click)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. $(document).bind("contextmenu",function(e){
  3. returnfalse;
  4. });
  5. });


2. 禁用搜索文本框(Disappearing search field text)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. $("input.text1").val("Enteryoursearchtexthere");
  3. textFill($('input.text1'));
  4. });
  5. functiontextFill(input){//inputfocustextfunction
  6. varoriginalvalue=input.val();
  7. input.focus(function(){
  8. if($.trim(input.val())==originalvalue){input.val('');}
  9. });
  10. input.blur(function(){
  11. if($.trim(input.val())==''){input.val(originalvalue);}
  12. });
  13. }


3. 新窗口打开链接(Opening links in a new window)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. //Example1:Everylinkwillopeninanewwindow
  3. $('a[href^="http://"]').attr("target","_blank");
  4. //Example2:Linkswiththerel="external"attributewillonlyopeninanewwindow
  5. $('a[@rel$='external']').click(function(){
  6. this.target="_blank";
  7. });
  8. });
  9. //howtouse
  10. <ahref="http://www.opensourcehunter.com"rel="external">openlink</a>


4. 检测浏览器(Detect browser)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. //TargetFirefox2andabove
  3. if($.browser.mozilla&&$.browser.version>="1.8"){
  4. //dosomething
  5. }
  6. //TargetSafari
  7. if($.browser.safari){
  8. //dosomething
  9. }
  10. //TargetChrome
  11. if($.browser.chrome){
  12. //dosomething
  13. }
  14. //TargetCamino
  15. if($.browser.camino){
  16. //dosomething
  17. }
  18. //TargetOpera
  19. if($.browser.opera){
  20. //dosomething
  21. }
  22. //TargetIE6andbelow
  23. if($.browser.msie&&$.browser.version<=6){
  24. //dosomething
  25. }
  26. //TargetanythingaboveIE6
  27. if($.browser.msie&&$.browser.version>6){
  28. //dosomething
  29. }
  30. });


5. 预加载图片(Preloading images)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. jQuery.preloadImages=function()
  3. {
  4. for(vari=0;i<arguments.length;i++)=""{=""jquery("<img="">").attr("src",arguments[i]);
  5. }
  6. }
  7. //howtouse
  8. $.preloadImages("image1.jpg");
  9. });
  10. </arguments.length;>


6. 样式筛选(CSS Style switcher)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. $("a.Styleswitcher").click(function(){
  3. //swicththeLINKRELattributewiththevalueinARELattribute
  4. $('link[rel=stylesheet]').attr('href',$(this).attr('rel'));
  5. });
  6. //howtouse
  7. //placethisinyourheader
  8. <linkrel="stylesheet"href="default.css"type="text/css">
  9. //thelinks
  10. <ahref="#"class="Styleswitcher"rel="default.css">DefaultTheme</a>
  11. <ahref="#"class="Styleswitcher"rel="red.css">RedTheme</a>
  12. <ahref="#"class="Styleswitcher"rel="blue.css">BlueTheme</a>
  13. });


7. 列高度相同(Columns of equal height)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. functionequalHeight(group){
  3. tallest=0;
  4. group.each(function(){
  5. thisHeight=$(this).height();
  6. if(thisHeight>tallest){
  7. tallest=thisHeight;
  8. }
  9. });
  10. group.height(tallest);
  11. }
  12. //howtouse
  13. $(document).ready(function(){
  14. equalHeight($(".left"));
  15. equalHeight($(".right"));
  16. });
  17. });


8. 字体大小调整(Font resizing)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. //Resetthefontsize(backtodefault)
  3. varoriginalFontSize=$('html').css('font-size');
  4. $(".resetFont").click(function(){
  5. $('html').css('font-size',originalFontSize);
  6. });
  7. //Increasethefontsize(biggerfont0
  8. $(".increaseFont").click(function(){
  9. varcurrentFontSize=$('html').css('font-size');
  10. varcurrentFontSizeNum=parseFloat(currentFontSize,10);
  11. varnewFontSize=currentFontSizeNum*1.2;
  12. $('html').css('font-size',newFontSize);
  13. returnfalse;
  14. });
  15. //Decreasethefontsize(smallerfont)
  16. $(".decreaseFont").click(function(){
  17. varcurrentFontSize=$('html').css('font-size');
  18. varcurrentFontSizeNum=parseFloat(currentFontSize,10);
  19. varnewFontSize=currentFontSizeNum*0.8;
  20. $('html').css('font-size',newFontSize);
  21. returnfalse;
  22. });
  23. });



9. 返回页面顶部(Smooth(animated) page scroll)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. $('a[href*=#]').click(function(){
  3. if(location.pathname.replace(/^\//,'')==this.pathname.replace(/^\//,'')
  4. &&location.hostname==this.hostname){
  5. var$target=$(this.hash);
  6. $target=$target.length&&$target
  7. ||$('[name='+this.hash.slice(1)+']');
  8. if($target.length){
  9. vartargetOffset=$target.offset().top;
  10. $('html,body')
  11. .animate({scrollTop:targetOffset},900);
  12. returnfalse;
  13. }
  14. }
  15. });
  16. //howtouse
  17. //placethiswhereyouwanttoscrollto
  18. <aname="top"></a>
  19. //thelink
  20. <ahref="#top">gototop</a>
  21. });



11. 获取鼠标的xy坐标(Get the mouse cursor x and y axis)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. $().mousemove(function(e){
  3. //displaythexandyaxisvaluesinsidethedivwiththeidXY
  4. $('#XY').html("XAxis:"+e.pageX+"|YAxis"+e.pageY);
  5. });
  6. //howtouse
  7. <divid="XY"></div>
  8. });



12. 验证元素是否为空(Verify if an Element is empty)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. if($('#id').html()){
  3. //dosomething
  4. }
  5. });

13. 替换元素(Replace a element)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. $('#id').replaceWith('
  3. <div>Ihavebeenreplaced</div>
  4. ');
  5. });

14. 延迟加载(jQuery timer callback functions)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. window.setTimeout(function(){
  3. //dosomething
  4. },1000);
  5. });

15. 移除单词(Remove a word)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. varel=$('#id');
  3. el.html(el.html().replace(/word/ig,""));
  4. });

16. 验证元素是否存在(Verify that an element exists in jQuery)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. if($('#id').length){
  3. //dosomething
  4. }
  5. });

17. 使整个DIV可点击(Make the entire DIV clickable)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. $("div").click(function(){
  3. //gettheurlfromhrefattributeandlaunchtheurl
  4. window.location=$(this).find("a").attr("href");returnfalse;
  5. });
  6. //howtouse
  7. <div><ahref="index.html">home</a></div>
  8. });

18. id和class切换(Switch between classes or id’s when resizing the window)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. functioncheckWindowSize(){
  3. if($(window).width()>1200){
  4. $('body').addClass('large');
  5. }
  6. else{
  7. $('body').removeClass('large');
  8. }
  9. }
  10. $(window).resize(checkWindowSize);
  11. });


19. 克隆对象(Clone a object)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. varcloned=$('#id').clone();
  3. //howtouse
  4. <divid="id"></div>
  5. });


20. 使元素居中屏幕(Center an element on the screen)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. jQuery.fn.center=function(){
  3. this.css("position","absolute");
  4. this.css("top",($(window).height()-this.height())/2+$(window).scrollTop()+"px");
  5. this.css("left",($(window).width()-this.width())/2+$(window).scrollLeft()+"px");
  6. returnthis;
  7. }
  8. $("#id").center();
  9. });


21. 自定义选择器(Write our own selector)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. $.extend($.expr[':'],{
  3. moreThen1000px:function(a){
  4. return$(a).width()>1000;
  5. }
  6. });
  7. $('.box:moreThen1000px').click(function(){
  8. //creatingasimplejsalertbox
  9. alert('Theelementthatyouhaveclickedisover1000pixelswide');
  10. });
  11. });


22. 统计元素个数(Count a element)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. $("p").size();
  3. });


23. 自定义Bullets(Use Your Own Bullets)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. $("ul").addClass("Replaced");
  3. $("ul>li").prepend("‒");
  4. //howtouse
  5. ul.Replaced{list-style:none;}
  6. });


24. 引用google分发的jQuery(Let Google host jQuery for you)

[javascript] view plain copy print ?
  1. //Example1
  2. <scriptsrc="http://www.google.com/jsapi"></script>
  3. <scripttype="text/javascript">
  4. google.load("jquery","1.2.6");
  5. google.setOnLoadCallback(function(){
  6. //dosomething
  7. });
  8. </script><scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"type="text/javascript"></script>
  9. //Example2:(thebestandfastestway)
  10. <scripttype="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>


25. 禁用jQuery动画(Disable jQuery animations)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. jQuery.fx.off=true;
  3. });


26. 防止不兼容冲突(No conflict-mode)

[javascript] view plain copy print ?
  1. $(document).ready(function(){
  2. var$jq=jQuery.noConflict();
  3. $jq('#id').show();
  4. });


jquery 速查表:





参考推荐:
jQuery
jQuery UI
14 days of jQuery
Learning jQuery
Cheatsheet jQuery 1.1.3
Improve your jQuery – 25 excellent tips
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值