![](/img/trans.png)
[英]How to set CSS transition to a new element or do the same with JavaScript
[英]css transition on element with value being set with javascript
我有一个样式表,其中包含为元素和一些模板 html 代码定义的过渡。 如果我延迟了我想在 javascript 中转换的属性的设置,它可以正常工作,但不能没有延迟。 我认为这是因为两者是同时评估的。 有没有更好的方法我应该这样做?
<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>
它不起作用,因为当您的代码运行时 div 不存在。 (它在 div 呈现之前运行。)将脚本移到正文的底部或将其包装在事件侦听器中,以便在页面完全加载时运行。
另外:您在该行的末尾有一个无关的}
,这可能会阻止它运行。
<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.