如何在Javascript循环中重绘HTML元素? [英] How do I make an HTML element repaint within a Javascript loop?

查看:221
本文介绍了如何在Javascript循环中重绘HTML元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些Javascript在HTML元素上动画化颜色变化,如下所示:

I have some Javascript which "animates" a colour change on an HTML element, as follows:

var element = document.getElementById("someid");
while (i < 255) {
    element.style.color = 'rgb(' + i + ',' + i + ',' + i + ')';
    i++;
    slowMeDown(); // This function runs for a few ms to slow the process down
}

可以看到,这将颜色从黑色变为白色,经过255之间的灰色阴影。

As you can see, this changes the color from black to white going through 255 shades of grey in between. I would like to make it visibly "fade" so that the user can see the text gradually disappear.

但是,浏览器(Chrome和IE - 尚未在Firefox上测试过) )只在函数结束时刷新,因此颜色只是从黑色变为白色。

However, the browser (Chrome and IE - not tested on Firefox yet) only refreshes at the end of the function, so the color simply changes from black to white. Does anyone know how to make the browser repaint during the loop so that I can see the text fade?

推荐答案

function changeColor()
{
    changeColorIncremental(0);
}

function changeColorIncremental(i)
{
    var element = document.getElementById("someid");

    element.style.color = 'rgb(' + i + ',' + i + ',' + i + ')';

    if (i < 255) {
        // Note the 50 millisecond wait below.  Decrease this to speed up
        // the transition, and increase it to slow it down.
        setTimeout('changeColorIncremental(' + (i + 1) + ')', 50);
    }
}

这篇关于如何在Javascript循环中重绘HTML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆