使用 jquery 动画方法在容器 div 周围移动框 div

Move box div around container div using jquery animate method

我是一名学生,刚接触 jquery 动画并尝试执行定向动画,其中每个方向都有一个相应的按钮,当单击任何按钮时,前一个动画停止。我也不希望无论单击哪个按钮方向,较小的 div 都会离开​​较大的 div。我设置 HTML 和 CSS 如下。

HTML

<!DOCTYPE html>
<html>
    <head>
        <title>
            Animation           
        </title>
        <link rel="stylesheet" type="text/css" href="animate.css" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript" src="animate.js"></script>
    </head>
    <body>
        <header>
            <h1>Animation in jQuery</h1>
        </header>
            <div id="btnPanel"> 
            <button id="button1">Up</button>  
            <button id="button2">Down</button>               
            <button id="button3">Left</button>               
            <button id="button4">Right</button>               
            <button id="button5">FadeOut</button>               
            <button id="button6">FadeIn</button>               
            <button id="button7">Blink</button>  
            <button id="button8">Reset</button>  

        </div>     

        <div id="container">
            <div id="box">
            </div>
            </div>


    </body>
</html>

CSS

#container
{
    height: 400px;
    width: 400px;
    background-color: powderblue;

}
#box
{
    height: 50px;
    width: 50px;
    position: absolute;
    background-color: blue;

}

编辑

我今天的所有四个方向都有些工作(是的)但是还没有掌握在不离开容器的情况下移动盒子的窍门。这是我的 Javascript 文件的一部分。

$(function MoveBox() {

    $("#button1").on("click", function MoveBox() {
        $("#box").animate({
            top: 150

        }, 1500)


    });

    $("#button2").on("click", function MoveBox() {
        $("#box").animate({
            bottom: 150

       }, 1500)
    });

    $("#button3").on("click", function MoveBox() {
        $("#box").animate({
            right: 150

        }, 1500)

    });

    $("#button4").on("click", function MoveBox() {
        $("#box").animate({

            left: 150

        }, 1500)

    });

});

几个小时以来,我一直在弄乱每个动画方法中的数字,到目前为止,向右走是唯一一个似乎按预期工作的方法,向下方向使框在容器外缩放,向左走其他方向或根本不起作用。有人可以用代码显示或解释使所有四个方向更顺利地工作的最佳方法吗?我以前没有做过很多像素数学...

这可能无法完全回答您的问题,但可能会帮助您指明正确的方向。我已经将两个示例放在一起,说明如何实现(我认为)您所要求的。

第一个 (https://jsfiddle.net/Lda5mxej/) 使用 if/else 语句对每个按钮应用操作。

$('button').on('click', function() {
    if ($(this).attr('id') === 'button1') { ... }
});

另一个 (https://jsfiddle.net/gkmey802/1/) 将 events/actions 附加到特定按钮。

$('#button1').on('click', function() { ... });

我给出了两个示例来帮助您理解可以采用不同的方法来实现相同的结果。