首页 文章

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

提问于
浏览
0

当我改变css中bg左侧的位置时,会发生转换 . 但是当我改变javascript中的位置时,没有过渡 .

要了解我正在谈论什么的步骤

css中的

  • 将bg从1366px更改为0.您将看到转换 .

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

  • 现在取消注释js代码 . 它会改变bg的位置,但没有过渡

这是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>

1 回答

  • 0

    这是因为您在css样式中使用了动画属性,因此为了使用Javascript进行动画制作,您还需要在JavaScript中定义自定义动画功能 .

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

相关问题