简体   繁体   English

使用javascript设置值的元素上的css转换

[英]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.我有一个样式表,其中包含为元素和一些模板 html 代码定义的过渡。 If I delay the setting of the attribute I want to transition in javascript it works fine but not without the delat.如果我延迟了我想在 javascript 中转换的属性的设置,它可以正常工作,但不能没有延迟。 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.它不起作用,因为当您的代码运行时 div 不存在。 (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. (它在 div 呈现之前运行。)将脚本移到正文的底部或将其包装在事件侦听器中,以便在页面完全加载时运行。

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>

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

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