当使用jquery动画命中外部div的边缘时停止div移动

时间:2013-03-19 20:04:48

标签: css jquery-animate position

我有一个带图像的div,并希望用户在div内移动它,但我不希望它超出div。 当div移动时,它仍将移出父区div并移动到我不想要的页面的其余部分

这是我的风格

<style>
#area{
    width: 500px;
    height: 500px;
    margin: auto;
    clear: both;
    background-color: red;
    position: absolute;
}
#one{
    width: 29px;
    height: 29px;
    background-image: url("images/fighter.png");
    position: relative;
    top: 50px;
}

button{
    float: left;
    width: 50px;
}
.gameControls{
    margin: auto;
    width: 150px;
}
.gameUp{
    margin: 0 0 0 50px;
}
.clear{
    clear: both;
}

这是我使用的jQuery脚本

<script>
    $(document).ready(function(){
        $('.gameUp').click(function(event){
            $("#one").animate({"top": "-=50px"}, "slow");
        });
        $('.gameLeft').click(function(event){
            $("#one").animate({"left": "-=50px"}, "slow");
        });
        $('.gameDown').click(function(event){
            $("#one").animate({"top": "+=50px"}, "slow");
        });
        $('.gameRight').click(function(event){
            $("#one").animate({"left": "+=50px"}, "slow");
        });
    });
</script>

我的身体代码

<div class="gameControls">
    <button class="gameUp">&uarr;</button>
    <div class="clear"></div>
    <button class="gameLeft">&larr;</button>
    <button class="gameDown">&darr;</button>
    <button class="gameRight">&rarr;</button>   
</div>
<div id="area">
<div id="one"></div>
</div>  

1 个答案:

答案 0 :(得分:0)

我不确定只能使用css来完成,因为topmarginpadding等可以分配给负值。

这是我的解决方案:

jsfiddle