简体   繁体   中英

css transition on element with value being set with javascript

I have a style sheet with a transition defined for an element and some template html code. If I delay the setting of the attribute I want to transition in javascript it works fine but not without the delat. I assume it's because both are evaluated at the same time. Is there a better way I should be doing this?

 <html> <head> <style> div { width:0%; height: 100px; background: red; transition: width 2s; } </style> <script> /* //this does work setTimeout(()=>{ document.querySelector("div").style.width="100%";},1000); */ //this does not work document.querySelector("div").style.width="200%";} </script> </head> <body> <h1>The transition Property</h1> <p>Hover over the div element below, to see the transition effect:</p> <div></div> <p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p> </body> </html>

It doesn't work because the div doesn't exist when your code runs. (It runs before the div is rendered.) Move the script to the bottom of the body or wrap it in an event listener so it runs when your page is fully loaded.

Also: You have an extraneous } at the end of that line which may be preventing it from running at all.

 <html> <head> <style> div { width: 0%; height: 100px; background: red; transition: width 2s; } </style> <script> /* //this does work setTimeout(()=>{ document.querySelector("div").style.width="100%";},1000); */ // wait for the page to load before running. window.addEventListener('load', () => { document.querySelector("div").style.width = "200%"; }) </script> </head> <body> <h1>The transition Property</h1> <p>Hover over the div element below, to see the transition effect:</p> <div></div> <p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p> </body> </html>

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