你如何设置带有淡入效果的“innerText”?

Jas*_*Lam 5 javascript css fadein css-animations

假设您有一个按钮来替换同一区域、同一页面内的段落。

您可以通过设置innerText或使每个开关textContent每次都淡入吗?

我现在使用keyframes将其不透明度从 0 更改为 1,但它仅适用于页面加载后的第一段。之后,每当我用 替换文本时innerText,效果根本不显示。

排队等候的所有文本都是用 JavaScript 硬编码的,而不是用 HTML 编码的——如果它做出改变的话。

Abh*_*lks 6

您将需要引入延迟或重新绘制。引入延迟可能是最简单的。

p.classList.add('hide');               // add the class
setTimeout(function() {                // delay and 
    p.textContent = txtList[idx];      // change text
    idx = (idx + 1) % txtList.length;
}, 500);
setTimeout(function() {                // delay and 
    p.classList.remove('hide')         // remove the class
}, 500);
Run Code Online (Sandbox Code Playgroud)

小提琴:http : //jsfiddle.net/abhitalks/rdnt9d5w/

片段:

p.classList.add('hide');               // add the class
setTimeout(function() {                // delay and 
    p.textContent = txtList[idx];      // change text
    idx = (idx + 1) % txtList.length;
}, 500);
setTimeout(function() {                // delay and 
    p.classList.remove('hide')         // remove the class
}, 500);
Run Code Online (Sandbox Code Playgroud)
var txtList = [
    'Lorem', 'ipsum', 'dolor', 'sit', 'amet', 
    'Lorem ipsum dolor sit amet'
], idx = 0, 
   p = document.getElementById('p1');

document.getElementById('btn1').addEventListener('click', fadein);

function fadein() {
    p.classList.add('hide');
    setTimeout(function() { 
        p.textContent = txtList[idx];
        idx = (idx + 1) % txtList.length;
    }, 500);
    setTimeout(function() { 
        p.classList.remove('hide')
    }, 500);
}
Run Code Online (Sandbox Code Playgroud)
p { opacity: 1; transition: all 0.5s; }
p.hide { opacity: 0; }
Run Code Online (Sandbox Code Playgroud)