Fork me on GitHub

实用jq代码片段【一】

链式操作

1
2
3
4
5
6
7
$(document).ready(function(){
$("button").click(function(){
$("#p1").slideUp(2000).slideDown(2000).css("color","red");
$("#div-log").html("<p>"+"实现链式(Chaining)操作"+"</p>");
//类似于+=
});
});

区分客户区,页面区,屏幕区

三者的X轴没什么说的,都一样,主要区别在于Y轴上,客户区,屏幕区的最大值固定,不会随着页面的滚动改变。页面区会随着滚动条的改变而变化。

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
27
28
29
30
31
32
33
//客户区
$(document).ready(function (){
$(document).mousemove(function(e){
getclient(e);
});
});
function getclient(e){
x=e.clientX; //当前可视窗口的距离
y=e.clientY;
$('#x').html("X:"+x+"Y:"+y);
}
//屏幕区
$(document).ready(function (){
$(document).mousemove(function(e){
getscreen(e);
});
});
function getscreen(e){
x=e.screenX; //屏幕的左上角为参考点距离屏幕边缘的距离
y=e.screenY;
$('#x').html("X:"+x+"Y:"+y);
}
//页面区
$(document).ready(function (){
$(document).mousemove(function(e){
getpage(e);
});
});
function getpage(e){
x=e.pageX; //相对于当前页面中的坐标(会随着滚动条的滚动而变化)
y=e.pageY;
$('#x').html("X:"+x+"Y:"+y);
}

左右自适应高度:

1
2
3
4
5
6
7
8
9
10
11
function $(id){
return document.getElementById(id);
}
(function autoheight(){
if($('left').offsetHeight>=$('right').offsetHeight){
$('right').style.height=$('left').offsetHeight+"px";
}else{
$('left').style.height=$('right').offsetHeight+"px";
}
})()
//需要注意的是必须自调用函数。

callback()函数

callback()函数在当前效果100%完成之后执行。在一个涉及动画的函数之后来执行语句,用callback()函数。

1
2
3
4
5
6
7
$(document).ready(function (){
$('button').click(function (){
$('p').hide(1000,function (){
alert("回调函数过程,激活一个提示框");
});
});
});

在新窗口打开链接

1
2
3
4
5
6
7
8
9
$(document).ready(function (){
$('.url').attr({target:"_blank"})
$('a[rel=ext]').click(function (){
$(this).attr('target','_blank')
});
});
function openurl(){
window.open('http://www.microsoft.com');
}

页面淡入淡出

1
2
3
4
5
6
7
$(document).ready(function (){
$('#fade').click(function (){
$('#div-fade').fadeToggle(1000);
$('#div-fade').fadeToggle(1000);
$("#div-fade").fadeTo(1000,0.2);
});
});

折叠展开

1
2
3
4
5
6
$(document).ready(function(){
$(".help h3").click(function(){
$(this).next("p").slideToggle("fast").siblings("p:visible").slideUp("fast");
//siblings表示取得一个包含匹配的元素集合中每一个元素的所有唯一同辈元素的元素集合
});
});

未完待续。。。

据说帅的人都赏给博主几块钱零花钱。