现在的位置: 首页 > 综合 > 正文

可以直接拿来用的15个jQuery代码片段

2013年08月29日 ⁄ 综合 ⁄ 共 1886字 ⁄ 字号 评论关闭

本文收集了15段非常实用的jQuery代码片段,你可以直接复制黏贴到代码里,但请开发者注意了,要理解代码再使用哦。下面就让我们一起来享受jQuery代码的魅力之处吧。

1.预加载图片

1
2
3
4
5
6
7
8
9
10
11
12
(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");

源码

2. 让页面中的每个元素都适合在移动设备上展示

1
2
3
4
5
6
7
8
9
10
11
var scr = document.createElement('script');
document.body.appendChild(scr);
scr.onload = function(){
    $('div').attr('class''').attr('id''').css({
        'margin' :
0,
        'padding' :
0,
        'width''100%',
        'clear':'both'
    });
};

源码

3.图像等比例缩放

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$(window).bind("load"function()
{
    // IMAGE RESIZE
    $('#product_cat_list
img'
).each(function()
{
        var maxWidth
= 120;
        var maxHeight
= 120;
        var ratio
= 0;
        var width
= $(
this).width();
        var height
= $(
this).height();
        if(width
> maxWidth){
            ratio = maxWidth / width;
            $(this).css("width",
maxWidth);
            $(this).css("height",
height * ratio);
            height = height * ratio;
        }
        var width
= $(
this).width();
        var height
= $(
this).height();
        if(height
> maxHeight){
            ratio = maxHeight / height;
            $(this).css("height",
maxHeight);
            $(this).css("width",
width * ratio);
            width = width * ratio;
        }
    });
    //$("#contentpage img").show();
    // IMAGE RESIZE
});

源码

4.返回页面顶部

1
2
3
4
5
6
7
8
// Back To Top
$(document).ready(function(){
  $('.top').click(function()
     $(document).scrollTo(0,500); 
  });
});
//Create a link defined with the class .top
<a href="#" class="top">Back
To Top</a>

源码

5.使用jQuery打造手风琴式的折叠效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

抱歉!评论已关闭.