每个程序员都会的 35 个 jQuery 小技巧

  1 收集的35个 jQuery 小技巧/代码片段,可以帮你快速开发.
  2 1. 禁止右键点击
  3 $(document).ready(function(){
  4     $(document).bind("contextmenu",function(e){
  5         return false;
  6     });
  7 });
  8 2. 隐藏搜索文本框文字
  9 Hide when clicked in the search field, the value.(example can be found below in the comment fields)
 10 
 11 $(document).ready(function() {
 12 $("input.text1").val("Enter your search text here");
 13    textFill($('input.text1'));
 14 });
 15 
 16     function textFill(input){ //input focus text function
 17      var originalvalue = input.val();
 18      input.focus( function(){
 19           if( $.trim(input.val()) == originalvalue ){ input.val(''); }
 20      });
 21      input.blur( function(){
 22           if( $.trim(input.val()) == '' ){ input.val(originalvalue); }
 23      });
 24 }
 25 3. 在新窗口中打开链接
 26 XHTML 1.0 Strict doesn’t allow this attribute in the code, so use this to keep the code valid.
 27 
 28 $(document).ready(function() {
 29    //Example 1: Every link will open in a new window
 30    $('a[href^="http://"]').attr("target", "_blank");
 31 
 32    //Example 2: Links with the rel="external" attribute will only open in a new window
 33    $('a[@rel$='external']').click(function(){
 34       this.target = "_blank";
 35    });
 36 });
 37 // how to use
 38 <a href="http://www.opensourcehunter.com" rel=external>open link</a>
 39 4. 检测浏览器
 40 注: 在版本jQuery 1.4中,$.support 替换掉了$.browser 变量
 41 $(document).ready(function() {
 42 // Target Firefox 2 and above
 43 if ($.browser.mozilla && $.browser.version >= "1.8" ){
 44     // do something
 45 }
 46 
 47 // Target Safari
 48 if( $.browser.safari ){
 49     // do something
 50 }
 51 
 52 // Target Chrome
 53 if( $.browser.chrome){
 54     // do something
 55 }
 56 
 57 // Target Camino
 58 if( $.browser.camino){
 59     // do something
 60 }
 61 
 62 // Target Opera
 63 if( $.browser.opera){
 64     // do something
 65 }
 66 
 67 // Target IE6 and below
 68 if ($.browser.msie && $.browser.version <= 6 ){
 69     // do something
 70 }
 71 
 72 // Target anything above IE6
 73 if ($.browser.msie && $.browser.version > 6){
 74     // do something
 75 }
 76 });
 77 5. 预加载图片
 78 This piece of code will prevent the loading of all images, which can be useful if you have a site with lots of images.
 79 $(document).ready(function() {
 80 jQuery.preloadImages = function()
 81 {
 82   for(var i = 0; i<ARGUMENTS.LENGTH; jQuery(?<img { i++)>").attr("src", arguments[i]);
 83   }
 84 }
 85 // how to use
 86 $.preloadImages("image1.jpg");
 87 });
 88 6. 页面样式切换
 89 $(document).ready(function() {
 90     $("a.Styleswitcher").click(function() {
 91         //swicth the LINK REL attribute with the value in A REL attribute
 92         $('link[rel=stylesheet]').attr('href' , $(this).attr('rel'));
 93     });
 94 // how to use
 95 // place this in your header
 96 <LINK rel=stylesheet type=text/css href="default.css">
 97 // the links
 98 <A href="#" rel=default.css>Default Theme</A>
 99 <A href="#" rel=red.css>Red Theme</A>
100 <A href="#" rel=blue.css>Blue Theme</A>
101 });
102 7. 列高度相同
103 如果使用了两个CSS列,使用此种方式可以是两列的高度相同。
104 $(document).ready(function() {
105 function equalHeight(group) {
106     tallest = 0;
107     group.each(function() {
108         thisHeight = $(this).height();
109         if(thisHeight > tallest) {
110             tallest = thisHeight;
111         }
112     });
113     group.height(tallest);
114 }
115 // how to use
116 $(document).ready(function() {
117     equalHeight($(".left"));
118     equalHeight($(".right"));
119 });
120 });
121 8. 动态控制页面字体大小
122 用户可以改变页面字体大小
123 $(document).ready(function() {
124   // Reset the font size(back to default)
125   var originalFontSize = $('html').css('font-size');
126     $(".resetFont").click(function(){
127     $('html').css('font-size', originalFontSize);
128   });
129   // Increase the font size(bigger font0
130   $(".increaseFont").click(function(){
131     var currentFontSize = $('html').css('font-size');
132     var currentFontSizeNum = parseFloat(currentFontSize, 10);
133     var newFontSize = currentFontSizeNum*1.2;
134     $('html').css('font-size', newFontSize);
135     return false;
136   });
137   // Decrease the font size(smaller font)
138   $(".decreaseFont").click(function(){
139     var currentFontSize = $('html').css('font-size');
140     var currentFontSizeNum = parseFloat(currentFontSize, 10);
141     var newFontSize = currentFontSizeNum*0.8;
142     $('html').css('font-size', newFontSize);
143     return false;
144   });
145 });
146 9. 返回页面顶部功能
147 For a smooth(animated) ride back to the top(or any location).
148 $(document).ready(function() {
149 $('a[href*=#]').click(function() {
150  if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
151  && location.hostname == this.hostname) {
152    var $target = $(this.hash);
153    $target = $target.length && $target
154    || $('[name=' + this.hash.slice(1) +']');
155    if ($target.length) {
156   var targetOffset = $target.offset().top;
157   $('html,body')
158   .animate({scrollTop: targetOffset}, 900);
159     return false;
160    }
161   }
162   });
163 // how to use
164 // place this where you want to scroll to
165 <A name=top></A>
166 // the link
167 <A href="#top">go to top</A>
168 });
169 10. 获得鼠标指针XY值
170 Want to know where your mouse cursor is?
171 $(document).ready(function() {
172    $().mousemove(function(e){
173      //display the x and y axis values inside the div with the id XY
174     $('#XY').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
175   });
176 // how to use
177 <DIV id=XY></DIV>
178 
179 });
180 11.返回顶部按钮
181 你可以利用 animate 和 scrollTop 来实现返回顶部的动画,而不需要使用其他插件。
182 // Back to top
183 $('a.top').click(function () {
184   $(document.body).animate({scrollTop: 0}, 800);
185   return false;
186 });
187 <!-- Create an anchor tag -->
188 <a href="#">Back to top</a>
189 改变 scrollTop 的值可以调整返回距离顶部的距离,而 animate 的第二个参数是执行返回动作需要的时间(单位:毫秒)。
190 12.预加载图片
191 如果你的页面中使用了很多不可见的图片(如:hover 显示),你可能需要预加载它们:
192 $.preloadImages = function () {
193   for (var i = 0; i < arguments.length; i++) {
194     $('<img>').attr('src', arguments[i]);
195   }
196 };
197 
198 $.preloadImages('img/hover1.png', 'img/hover2.png');
199 13.检查图片是否加载完成
200 有时候你需要确保图片完成加载完成以便执行后面的操作:
201 $('img').load(function () {
202   console.log('image load successful');
203 });
204 你可以把 img 替换为其他的 ID 或者 class 来检查指定图片是否加载完成。
205 14.自动修改破损图像
206 如果你碰巧在你的网站上发现了破碎的图像链接,你可以用一个不易被替换的图像来代替它们。添加这个简单的代码可以节省很多麻烦:
207 $('img').on('error', function () {
208   $(this).prop('src', 'img/broken.png');
209 });
210 即使你的网站没有破碎的图像链接,添加这段代码也没有任何害处。
211 15.鼠标悬停(hover)切换 class 属性
212 假如当用户鼠标悬停在一个可点击的元素上时,你希望改变其效果,下面这段代码可以在其悬停在元素上时添加 class 属性,当用户鼠标离开时,则自动取消该 class 属性:
213 $('.btn').hover(function () {
214   $(this).addClass('hover');
215   }, function () {
216     $(this).removeClass('hover');
217   });
218 你只需要添加必要的CSS代码即可。如果你想要更简洁的代码,可以使用 toggleClass 方法:
219 $('.btn').hover(function () { 
220   $(this).toggleClass('hover'); 
221 });
222 注:直接使用CSS实现该效果可能是更好的解决方案,但你仍然有必要知道该方法。
223 16.禁用 input 字段
224 有时你可能需要禁用表单的 submit 按钮或者某个 input 字段,直到用户执行了某些操作(例如,检查“已阅读条款”复选框)。可以添加 disabled 属性,直到你想启用它时:
225 $('input[type="submit"]').prop('disabled', true);
226 你要做的就是执行 removeAttr 方法,并把要移除的属性作为参数传入:
227 $('input[type="submit"]').removeAttr('disabled');
228 17.阻止链接加载
229 有时你不希望链接到某个页面或者重新加载它,你可能希望它来做一些其他事情或者触发一些其他脚本,你可以这么做:
230 $('a.no-link').click(function (e) {
231   e.preventDefault();
232 });
233 18.切换 fade/slide
234 fade 和 slide 是我们在 jQuery 中经常使用的动画效果,它们可以使元素显示效果更好。但是如果你希望元素显示时使用第一种效果,而消失时使用第二种效果,则可以这么做:
235 // Fade
236 $('.btn').click(function () {
237   $('.element').fadeToggle('slow');
238 });
239 // Toggle
240 $('.btn').click(function () {
241   $('.element').slideToggle('slow');
242 });
243 19.简单的手风琴效果
244 这是一个实现手风琴效果快速简单的方法:
245 // Close all panels
246 $('#accordion').find('.content').hide();
247 // Accordion
248 $('#accordion').find('.accordion-header').click(function () {
249   var next = $(this).next();
250   next.slideToggle('fast');
251   $('.content').not(next).slideUp('fast');
252   return false;
253 });
254 20.让两个 DIV 高度相同
255 有时你需要让两个 div 高度相同,而不管它们里面的内容多少。可以使用下面的代码片段:
256 var $columns = $('.column');
257 var height = 0;
258 $columns.each(function () {
259   if ($(this).height() > height) {
260     height = $(this).height();
261   }
262 });
263 $columns.height(height);
264 这段代码会循环一组元素,并设置它们的高度为元素中的最大高。
265 21. 验证元素是否为空
266 This will allow you to check if an element is empty.
267 $(document).ready(function() {
268   if ($('#id').html()) {
269    // do something
270    }
271 });
272 22. 替换元素
273 $(document).ready(function() {
274    $('#id').replaceWith('
275 <DIV>I have been replaced</DIV>
276 
277 ');
278 });
279 23. jQuery延时加载功能
280 $(document).ready(function() {
281    window.setTimeout(function() {
282      // do something
283    }, 1000);
284 });
285 24. 移除单词功能
286 $(document).ready(function() {
287    var el = $('#id');
288    el.html(el.html().replace(/word/ig, ""));
289 });
290 25. 验证元素是否存在于jquery对象集合中
291 $(document).ready(function() {
292    if ($('#id').length) {
293   // do something
294   }
295 });
296 26. 使整个DIV可点击
297 $(document).ready(function() {
298     $("div").click(function(){
299       //get the url from href attribute and launch the url
300       window.location=$(this).find("a").attr("href"); return false;
301     });
302 // how to use
303 <DIV><A href="index.html">home</A></DIV>
304 
305 });
306 27. ID与Class之间转换
307 当改变Window大小时,在ID与Class之间切换
308 $(document).ready(function() {
309    function checkWindowSize() {
310     if ( $(window).width() > 1200 ) {
311         $('body').addClass('large');
312     }
313     else {
314         $('body').removeClass('large');
315     }
316    }
317 $(window).resize(checkWindowSize);
318 });
319 28. 克隆对象
320 $(document).ready(function() {
321    var cloned = $('#id').clone();
322 // how to use
323 <DIV id=id></DIV>
324 
325 });
326 29. 使元素居屏幕中间位置
327 $(document).ready(function() {
328   jQuery.fn.center = function () {
329       this.css("position","absolute");
330       this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
331       this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
332       return this;
333   }
334   $("#id").center();
335 });
336 30. 写自己的选择器
337 $(document).ready(function() {
338    $.extend($.expr[':'], {
339        moreThen1000px: function(a) {
340            return $(a).width() > 1000;
341       }
342    });
343   $('.box:moreThen1000px').click(function() {
344       // creating a simple js alert box
345       alert('The element that you have clicked is over 1000 pixels wide');
346   });
347 });
348 31. 统计元素个数
349 $(document).ready(function() {
350    $("p").size();
351 });
352 32. 使用自己的 Bullets
353 $(document).ready(function() {
354    $("ul").addClass("Replaced");
355    $("ul > li").prepend("? ");
356  // how to use
357  ul.Replaced { list-style : none; }
358 });
359 33. 引用Google主机上的Jquery类库
360 //Example 1
361 <SCRIPT src="http://www.google.com/jsapi"></SCRIPT>
362 <SCRIPT type=text/javascript>
363 google.load("jquery", "1.2.6");
364 google.setOnLoadCallback(function() {
365     // do something
366 });
367 </SCRIPT><SCRIPT type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></SCRIPT>
368 
369  // Example 2:(the best and fastest way)
370 <SCRIPT type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></SCRIPT>
371 34. 禁用Jquery(动画)效果
372 $(document).ready(function() {
373     jQuery.fx.off = true;
374 });
375 35. 与其他Javascript类库冲突解决方案
376 $(document).ready(function() {
377    var $jq = jQuery.noConflict();
378    $jq('#id').show();
379 });

 

posted @ 2015-11-11 15:17  博斯芮网络科技  阅读(159)  评论(0编辑  收藏  举报