简体   繁体   English

使用transition-delay选项(css)和JS进行div移动

[英]Use the transition-delay option (css) and JS to make a div move

I want to create a function that moves a block smoothly. 我想创建一个可以平滑移动块的函数。 I prefer to use the CSS option 'transition-duration' for this, but it doesn't seem to work for the position. 我更喜欢为此使用CSS选项'transition-duration',但它似乎不适用于该职位。 I checked, and it does work for background-color... 我检查了一下,它确实适用于背景色...

CSS file CSS文件

 #cart {
            position: relative;
            transition-duration: 0.5s;
            background-color: green;
        }

JS file JS文件

function start() {
    document.getElementById("cart").innerHTML = "test2";
    document.getElementById("cart").style.left = "100";
    document.getElementById("cart").style.background = "gray";
}

So the background-color does change in 2 seconds instead of instantly while the position just changes the instant you use the function. 因此,背景颜色的确会在2秒内改变,而不是立即改变,而位置只是在您使用该功能的瞬间改变。 Is there a way to use the 'transition-duration' for the style.left in JS? 有没有一种方法可以将'transition-duration'用作JS中的style.left? Or do I have to use something else to make the div move smoothly? 还是我必须使用其他方法使div平稳移动?

Use transition: left 0.5s linear; 使用过渡:左0.5s线性; as you haven't said what property you're transitioning. 因为您还没有说要转换的属性。

Also, put the styles you want to change to in a class and apply the class with js instead. 另外,将要更改的样式放在类中,然后使用js应用该类。

Also, you probably want to transition an absolute item inside a relative container, not apply 'left' to a relative element. 另外,您可能希望在相对容器内转换绝对项目,而不是对相对元素应用“ left”。

The CSS for "left" isn't declared in the CSS before it's added in the JS. 在JS中添加“ left”的CSS之前,没有在CSS中声明它。 Also "100" is an invalid value for CSS position (note the added "px" in the following example). 另外,“ 100”是CSS位置的无效值(请注意,在以下示例中添加了“ px”)。

JSFiddle: https://jsfiddle.net/MissionMike/adj4j6tr/ JSFiddle: https ://jsfiddle.net/MissionMike/adj4j6tr/

HTML: HTML:

<div id="cart">TEST</div>

CSS: CSS:

#cart {
  position: relative;
  transition-duration: 0.5s;
  background-color: green;
  left: 0;
}

JS: JS:

document.getElementById("cart").innerHTML = "test2";
document.getElementById("cart").style.left = "100px";
document.getElementById("cart").style.background = "gray";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM