分享10个很棒的jQuery代码片段

jQuery使用户能更方便地处理HTML documents、events,以及动画效果,并且方便地为网站提供AJAX交互。jQuery的另一个比较大的优势是,它拥有一套很好的文档说明,其中的各种应用也说得很详细,同时还有优秀的插件可供开发组来选择。jQuery能够使用户的html页保持代码和html内容分离,也就是说,不用再在html里面插入一堆js来调用命令了,只需定义id即可。

[代码] 图片预加载


(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");

[代码] 在新窗口打开链接 (target=”blank”)


$('a[@rel$='external']').click(function(){
     this.target = "_blank";
});
/*
   Usage:
   <a href="http://www.idbshare.com" rel="external">idbshare.com</a>
*/

[代码] 当支持 JavaScript 时为 body 增加 class


/* 该代码只有1行,但是最简单的用来检测浏览器是否支持 JavaScript 的方法
    如果支持 JavaScript 就在 body 元素增加一个 hasJS 的 class */
$('body').addClass('hasJS');

[代码] 平滑滚动页面到某个锚点


$(document).ready(function() {
    $("a.topLink").click(function() {
        $("html, body").animate({
            scrollTop: $($(this).attr("href")).offset().top + "px"
        }, {
            duration: 500,
            easing: "swing"
        });
        return false;
    });
});

[代码] 鼠标滑动时的渐入和渐出


$(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
    });
});

[代码] 制作等高的列


var max_height = 0;
$("div.col").each(function(){
    if ($(this).height() > max_height) { max_height = $(this).height(); }
});
$("div.col").height(max_height);

[代码] 在一些老的浏览器上启用 HTML5 的支持


(function(){
    if(!/*@cc_on!@*/0)
        return;
    var e = "abbr,article,aside,audio,bb,canvas,datagrid,datalist,details,dialog,eventsource,figure,footer,header,hgroup,mark,menu,meter,nav,output,progress,section,time,video".split(','),i=e.length;while(i--){document.createElement(e[i])}
})()
//然后在head中引入该js
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

[代码] 测试浏览器是否支持某些 CSS3 属性


var supports = (function() {
   var div = document.createElement('div'),
      vendors = 'Khtml Ms O Moz Webkit'.split(' '),
      len = vendors.length;
   return function(prop) {
      if ( prop in div.style ) return true;
      prop = prop.replace(/^[a-z]/, function(val) {
         return val.toUpperCase();
      });
      while(len--) {
         if ( vendors[len] + prop in div.style ) {
            // browser supports box-shadow. Do what you need.
            // Or use a bang (!) to test if the browser doesn't.
            return true;
         }
      }
      return false;
   };
})();
if ( supports('textShadow') ) {
   document.documentElement.className += ' textShadow';

[代码] 获取 URL 中传递的参数


$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (!results) { return 0; }
    return results[1] || 0;
}

[代码] 禁用表单的回车键提交


$("#form").keypress(function(e) {
  if (e.which == 13) {
    return false;
  }
});