我是一名学生,对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/)将事件/动作附加到特定按钮。
$('#button1').on('click', function() { ... });
我提供了两个示例,以帮助您了解可以采用不同的方法来获得相同的结果。