今天在学习使用jQuery里面的动画功能,animate(),为了方便显示及显示效果测试,打算采用toggle函数,使动画能来回的移动。写了以下一段代码(纯为了学习的简陋代码):
<html>
<head>
<script type="text/javascript" src="./scripts/jquery-1.10.2.js"></script>
<style type="text/css">
#pic1{
position: relative;
width: 100px;
height:150px;
top: 100px;
border: 1px dotted;
background-color: #aaa;
cursor:pointer;
text-align:center;
padding: 70px;
left: 100px;
}
#content{
display: none;
}
</style>
</head>
<body>
<script>
$(function(){
$("#pic1").click(function(){
$(this).animate({left: "500px"}, 1000);
});
</script>
<div id="pic1">
click me!
</div>
</body>
</html>
以上代码可以让页面中的div方块移动起来,但是加入toggle()之后,出现了对应div直接消失的问题:
$("#pic1").toggle(function(){
$(this).animate({left: "500px"}, 1000);
}, function(){
$(this).animate({left: "100px"}, 1000);
});
查阅文档后发现,toggle在1.9以后的版本中就只支持隐藏功能了,因此只能通过“多写多得到“(jQuery号称少写多的来着,去除toogle()的使用方法,让我肃然”不明觉挫“也哉!!)。
这里做了一个简单的判断,如果div的左边距大于500px则向左移,反之向右:
$(function(){
$("#pic1").click(function(){
var $orgLeft = $("#pic1").css("left");
var $distance = 500;
var $endLeft;
if(parseInt($orgLeft) > 500){
$endLeft = parseInt($orgLeft) - parseInt($distance);
}
else{
$endLeft = parseInt($orgLeft) + parseInt($distance);
}
$(this).animate({left: $endLeft}, 1000);
});
});
抛砖引玉,希望没砸到人: )
<html>
<head>
<script type="text/javascript" src="./scripts/jquery-1.10.2.js"></script>
<style type="text/css">
#pic1{
position: relative;
width: 100px;
height:150px;
top: 100px;
border: 1px dotted;
background-color: #aaa;
cursor:pointer;
text-align:center;
padding: 70px;
left: 100px;
}
#content{
display: none;
}
</style>
</head>
<body>
<script>
$(function(){
$("#pic1").click(function(){
$(this).animate({left: "500px"}, 1000);
});
</script>
<div id="pic1">
click me!
</div>
</body>
</html>
以上代码可以让页面中的div方块移动起来,但是加入toggle()之后,出现了对应div直接消失的问题:
$("#pic1").toggle(function(){
$(this).animate({left: "500px"}, 1000);
}, function(){
$(this).animate({left: "100px"}, 1000);
});
查阅文档后发现,toggle在1.9以后的版本中就只支持隐藏功能了,因此只能通过“多写多得到“(jQuery号称少写多的来着,去除toogle()的使用方法,让我肃然”不明觉挫“也哉!!)。
这里做了一个简单的判断,如果div的左边距大于500px则向左移,反之向右:
$(function(){
$("#pic1").click(function(){
var $orgLeft = $("#pic1").css("left");
var $distance = 500;
var $endLeft;
if(parseInt($orgLeft) > 500){
$endLeft = parseInt($orgLeft) - parseInt($distance);
}
else{
$endLeft = parseInt($orgLeft) + parseInt($distance);
}
$(this).animate({left: $endLeft}, 1000);
});
});
抛砖引玉,希望没砸到人: )