简体   繁体   English

CSS过渡:使用JavaScript触发

[英]CSS Transitions: Trigger with JavaScript

I have previously asked a question about triggering a CSS transition with JavaScript & setTimeout ( JavaScript: Trigger CSS Transition with window.setTimeout ). 我之前曾问过一个有关使用JavaScript和setTimeout 触发CSS转换的问题JavaScript:使用window.setTimeout触发CSS转换 )。 This question is trying to get more information on that. 这个问题试图获得更多的信息。

I have a function which changes the content and fades in a paragrapn p#test : 我有一个函数,它可以更改内容并在parappnp p#test淡入淡出:

function test() {
    var done=false;
    var p=document.querySelector('p#test');
    window.setInterval(doit,4000);
    var data=0;

    function doit() {
        p.removeAttribute('on');    //  1
        p.offsetHeight;             //  2   force update
        p.innerHTML=data++;         //  3
        p.setAttribute('on',null);  //  4
    }
}

The CSS is: CSS是:

p#test {
    opacity: 0;
}
p#test[on] {
    transition: opacity 1s;
    opacity: 1;
}

I note that the transition property must be set in the p#test[on] rule . 我注意到必须在p#test[on]规则中设置 transition属性。 If set for the p#test rule, it will not work. 如果为p#test规则设置,它将不起作用。

I find that steps 2 & 3 above can be interchanged. 我发现上面的步骤23可以互换。

However, I cannot get it working at all if I try to set the properties in JavaScript alone: 但是,如果我尝试仅在JavaScript中设置属性,我将使其无法正常工作:

function doit() {       //  DOES NOT WORK
    p.style.opacity=0;
    p.offsetHeight;
    p.innerHTML=data++;
    p.style.opacity=1;
}

So I conclude: 所以我得出结论:

  • Changing an attribute (or class) in JavaScript will trigger a CSS transition 在JavaScript中更改属性(或类)将触发CSS转换
  • Changing a CSS property in JavaScript will not trigger a transition 在JavaScript中更改CSS属性不会触发过渡
  • The transition will only be triggered if the transition property in in the triggered rule. 仅当触发规则中的transition属性为时,才会触发transition

Sorry about the long preamble. 抱歉,序言很长。 The question is: 问题是:

Precisely what JavaScript will actually trigger a CSS transition? 究竟哪种 JavaScript实际上会触发CSS转换? Is it only a change of class or attribute, or will anything else work? 它仅仅是改变类或属性,还是其他任何方法都能起作用?

I have added a Fiddle here: https://jsfiddle.net/comparity/a7qt297m/ 我在这里添加了小提琴: https : //jsfiddle.net/comparity/a7qt297m/

Dumb question, but does the base element ( p#test ) also have the transition property on it? 愚蠢的问题,但是基础元素( p#test )上是否也具有transition属性? In your example code, the transition property is only there for the "on" state. 在示例代码中,过渡属性仅在“ on”状态下存在。

If that's not it, it could be because you're changing the opacity from 0 to 1 in immediate succession in the same function. 如果不是这样,可能是因为您在同一函数中立即将不透明度从0更改为1。 See if a tiny setTimeout can make a difference for the opacity=1 line. 查看微小的setTimeout是否可以使opacity = 1行有所作为。

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

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