【问题标题】:Stop div moving when hits the edge of external dive with jquery annimate使用 jquery animate 碰到外部 div 的边缘时停止 div 移动
【发布时间】:2013-03-19 20:04:48
【问题描述】:

我有一个带有图像的 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>  

【问题讨论】:

    标签: css jquery-animate position


    【解决方案1】:

    我不确定是否可以仅使用 css 来完成,因为 topmarginpadding 等可以分配为负值。

    这是我的 js 解决方案:

    jsfiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多