简体   繁体   中英

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. I checked, and it does work for background-color...

CSS file

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

JS file

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. Is there a way to use the 'transition-duration' for the style.left in JS? Or do I have to use something else to make the div move smoothly?

Use transition: left 0.5s linear; 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.

Also, you probably want to transition an absolute item inside a relative container, not apply 'left' to a relative element.

The CSS for "left" isn't declared in the CSS before it's added in the JS. Also "100" is an invalid value for CSS position (note the added "px" in the following example).

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

HTML:

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

CSS:

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

JS:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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