我正在尝试使用 Jquery 为窗口右侧的 div 设置动画。我还使用 Jquery UI 来更改 div 的颜色。我也在为整个窗口的 div 设置动画。不过,我只是在试验 jquery 动画,没什么重要的。这是我到目前为止的代码:
HTML:
<div id="box1"></div>
<button type="button" id="btn"> Click Me! </button>
CSS:
#box1{
width: 200px;
height: 200px;
background-color: red;
border: 0px solid black;
border-radius: 0px;
position: relative;
}
#btn{
position: fixed;
top: 600px;
display: table-cell;
font-size: 30px;
}
JQuery:
var allow = true;
var animating = false;
$("#btn").click(function(){
if(allow == true){
if(!animating){
animating = true;
$("#btn").hide();
$("#box1").animate({backgroundColor: "yellow", borderWidth: "5px"}, 1000, "linear").animate({left: "500px"}, 1000).animate({top: "500px"}, 1000);
$("#box1").animate({left: "1000px", top: "0px"}, 1000).animate({left: "500px"}, 1000).animate({top: "500px"}, 1000, function(){
allow = false;
animating = false;
$("#btn").show().text("Click Me Aagain!");
});
}
} else {
if(!animating){
$("#btn").hide();
animating = true;
$("#box1").animate({top: 0}, 1000).animate({left: 0}, 1500).animate({backgroundColor: "red", borderRadius: 0, borderWidth: 0, width: "100px", height: "100px"}, 1000, function(){
$("#btn").show().text("Start Over!");
});
animating = false;
allow = true;
}
}
});
顶部的第一个变量是在两个不同的动画序列之间切换。接下来是确保动画不会被错误触发两次。我试图一直向右移动的元素是#box1,我希望它在第一个序列的末尾这样做!
感谢您的帮助!
最佳答案
有 2 个选项可以让方框动画到区域的右边缘。
1) 您可以设置 css “left: auto”,并为 css “right:0”设置动画。为此,您需要采取一些额外的步骤。您需要将 css“position: absolute”设置为该框,并且需要将框包装在具有 css“position:relative”且宽度为 100% 的 div 中。这样,盒子就知道右边缘在哪里,因为它最直接的父级有 css“position:relative”正在设置边界。执行此选项需要进行一些微调,因为在左右位置动画之间切换会导致一些跳跃。
2) 您可以使用此选项继续为左侧位置设置动画,但要使其向右设置动画,您需要 jquery 来计算页面的宽度,并减去框的宽度。它看起来像这样:
左:($(文档).outerWidth() - $('#box1').outerWidth())
关于javascript - 使用 Jquery 将元素动画到窗口的右边缘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26042773/