簡體   English   中英

使用javascript設置值的元素上的css轉換

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM