1

I am trying to animate a div when clicking on the document using jQuery by increasing the x-position of that div.

I don't want the div to go out of my sight while it is animating; if the div went out of my screen I want to bring it back.

This is my code:

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body{
    overflow: hidden;
}
div {
    position: absolute;
    left:10px;
    top:10px;
    width:20px;
    height:20px;
    background-color:green;
}
</style>
<script type="text/javascript">
$(function(){
    $(document).click(function(){
        if($("div").offset().left > (parseInt($(window).width()))){
            $("div").animate({"top":'+=20'},1000);
            $("div").animate({"left": '8' },1000);
        }else{
            $("div").animate({"left":'+=400'},1000);
        }
    });
});
</script>
</head>
<body>
<div></div>
</body>
</html>

​</p>

4

1 回答 1

4

参考 http://jsfiddle.net/YV747/3/

$(function(){
    $(document).click(function(){
        $("#pointer").stop(0,0);

        if(($("#pointer").offset().left+100) > $(window).width()){
            $("#pointer").animate({"top":'+=20',"left":8},1000);
            //$("#pointer").animate({"left": '8' },1000);
        }else{
            $("#pointer").animate({"left":'+=400'},1000);
        }
    });
});

看线if(($("#pointer").offset().left+100) > $(window).width()){

我给了 100,你可以给 400 或任何适合你的值。

注意:不要在简单的div始终使用上使用代码,id否则它将作用于文档中的所有 div。

于 2012-07-19T10:48:22.897 回答