簡體   English   中英

在javascript中更改元素的位置時沒有過渡

[英]There is no transition when change position of element in javascript

當我更改CSS中bg的位置時,會有一個過渡。 但是,當我更改javascript中的位置時,沒有過渡。

遵循步驟查看即時消息

  1. 在CSS中,將左bg從1366px更改為0。您將看到一個過渡。

2.將背景色的位置更改回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樣式中使用了animation屬性,因此要使用Java動畫制作動畫,還需要在JavaScript中定義自定義動畫功能。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM