本文收集了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 for ( var i var cacheImage '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' : 'padding' : '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 ).each( function () var maxWidth var maxHeight var ratio var width this ).width(); var height this ).height(); if (width ratio = maxWidth / width; $( this ).css( "width" , $( this ).css( "height" , height = height * ratio; } var width this ).width(); var height this ).height(); if (height ratio = maxHeight / height; $( this ).css( "height" , $( this ).css( "width" , 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 |
5.使用jQuery打造手风琴式的折叠效果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|