gpt4 book ai didi

html - 动画只能应用于 'absolute' 定位的元素吗?

转载 作者:行者123 更新时间:2023-11-28 10:24:57 27 4
gpt4 key购买 nike

我正在尝试使用 DOM 为对象设置动画,并在其 CSS 属性 position 未设置为“absolute”时努力为元素设置动画。下面是我的代码:

我创建了一个圆形 HTML 元素并尝试将它移动 45 度。有什么方法可以为未定位为 absolute 的 HTML 元素对象设置动画?

 x = 10;

function on_click() {

var myCurvyMovement = document.getElementById("circle");
myCurvyMovement.style.left = 0.5 * x;
myCurvyMovement.style.top = 1 + x

x += 10;

}
 #circle {
position: absolute;
width: 100px;
height: 100px;
background: red;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
}

/* Cleaner, but slightly less support: use "50%" as value */
#divBox {
position: static
}
<body>
<button style="display:block" onclick="on_click()">Move the box</button>
<div id="circle">
</div>
</body>

最佳答案

我不会考虑 left/right 来制作动画。正如您所注意到的,它不会在所有情况下都有效,因为它需要定位元素。即使在使用定位元素时,relativeabsolutefixed 之间的行为也不相同,因为每个元素都有自己的引用 顶部/左侧

对于这种情况,最好考虑 transform您可以将其应用于任何元素 ( shouldn't be an inline element ),并且所有元素的移动引用都是相同的。你也会有更好的表现。

x = 10;

function on_click() {

var myCurvyMovement = document.getElementById("circle");
myCurvyMovement.style.transform = "translate(" + (0.5 * x)+"px,"+(1 + x)+"px)";
x += 10;

}
#circle {
width: 100px;
height: 100px;
background: red;
border-radius: 50px;
transition:0.5s all; /*to have a smooth movement*/
}
<body>
<button style="display:block" onclick="on_click()">Move the box</button>
<div id="circle">
</div>
</body>

关于html - 动画只能应用于 'absolute' 定位的元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54996064/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com