简体   繁体   English

CSS 转换属性在通过 JS 触发时不起作用 function

[英]CSS transform property not working when it is triggered through JS function

The transform property will work in some instances, but what am I doing wrong in this instance: transform 属性在某些情况下会起作用,但在这种情况下我做错了什么:

  1. Making a span element and putting it in the innerHTML of a pre tag制作一个 span 元素并将其放在 pre 标签的 innerHTML 中
  2. Span element has opacity: 0, and transform: 2s. Span 元素的不透明度为 0,变换为 2s。
  3. Selecting this span element, and then changing opacity to 0.选择此跨度元素,然后将不透明度更改为 0。
  4. All this done in a function, shown below:所有这一切都在一个 function 中完成,如下所示:

 const lineText = document.getElementById("line-text"); function DisplayText() { lineText.innerHTML += "<span>TEXT;</span>". lineText.getElementsByTagName("span")[0].style;opacity = 1; } DisplayText();
 span { opacity: 0; transition: 1s; }
 <pre id="line-text"></pre>

This always results in the element just appearing instantly.这总是会导致元素立即出现。 Any ideas what's wrong?任何想法出了什么问题?

 const lineText = document.getElementById("line-text"); function DisplayText() { lineText.innerHTML += "<span>TEXT;</span>". setTimeout(() => { lineText.getElementsByTagName("span")[0].style;opacity = 1, }; 10); } DisplayText();
 span { opacity: 0; transition: 1s; }
 <html> <head> <title>Parcel Sandbox</title> <meta charset="UTF-8" /> </head> <body> <pre id="line-text"></pre> </body> </html>

I think if you add it in this way it will do what you want:我认为如果您以这种方式添加它,它将执行您想要的操作:

lineText.getElementsByTagName("span")[0].style = {
   transition:'1s',
   opacity:1
 };

or if it's still not working,I think that would because of by the time that javascript is appending "TEXT," to lineText is applying style as well , so we need a small delay或者如果它仍然不起作用,我认为那是因为到 javascript 将“TEXT”附加到 lineText 时也在应用样式,所以我们需要一个小的延迟

 setTimeout(() => {
     lineText.getElementsByTagName("span")[0].style.opacity = 1;
   }, 10);

what I did is I let js to complete it's tasks in it's thread and then add style我所做的是让 js 在它的线程中完成它的任务,然后添加样式

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

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