gpt4 book ai didi

javascript - 在javascript中更改元素位置时没有转换

转载 作者:行者123 更新时间:2023-11-28 02:45:25 25 4
gpt4 key购买 nike

当我在 css 中更改 bg 左侧的位置时,会出现一个过渡。但是当我在 javascript 中更改位置时,没有转换。

要遵循的步骤以了解我在说什么

  1. 在 css 中将 bg left 从 1366px 更改为 0。您将看到一个过渡。

2.将bg的位置改回1366px。

  1. 现在取消注释 js 代码。它会改变背景位置,但没有过渡

这是 codepen,我认为你不能更改 stackoverflow 上的代码

https://codepen.io/anon/pen/oGKMpm

var bg = document.getElementsByClassName('bg');


// uncomment the code below. there is no transition

// bg[0].style.left ='0';
* {
padding: 0;
margin: 0;
}

html, body, .bg {
height: 100%;
width: 100%;
}

.bg {
position: absolute;
background: blue;
transition: all 0.5s linear;

/* change this to 0px. there will be a transition. change it back to 1366px. and then uncomment the javascript code */
left: 1366px;
}
<div class="bg"></div>

最佳答案

这是因为您在 css 样式中使用了动画属性,因此为了使用 Javascript 制作动画,您还需要在 JavaScript 中定义自定义动画函数。

(function(){
var bg = document.getElementsByClassName('bg');
var pos = 1366;
setInterval(function(){ bg[0].style.left = --pos;}, 10);
})();

关于javascript - 在javascript中更改元素位置时没有转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46946816/

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