不能多次更改 html 元素的不透明度

cant change html element's opacity more than one time

我希望我的 <div> 慢慢变得可见!

这是我的代码:

var Thread = {
    sleep: function(ms) {
        var start = Date.now();

        while (true) {
            var clock = (Date.now() - start);
            if (clock >= ms) break;
        }

    }
};



function anime()
{

    var elem = document.getElementById('tagd');


    document.getElementById('tagd').style.opacity += 0.4;
    console.log(document.getElementById('tagd').style.opacity);

    Thread.sleep(1000);

    document.getElementById('tagd').innerHTML ="<h1>Sometext</h1>";
    console.log("do");
function frame()
    {
            num = 0.1;
            elem.style.opacity += num;

    }


}

它有效,但是当我将其更改为:

var Thread = {
    sleep: function(ms) {
        var start = Date.now();

        while (true) {
            var clock = (Date.now() - start);
            if (clock >= ms) break;
        }

    }
};



function anime()
{

    var elem = document.getElementById('tagd');


    document.getElementById('tagd').style.opacity += 0.4;
    console.log(document.getElementById('tagd').style.opacity);

    Thread.sleep(1000);



document.getElementById('tagd').style.opacity += 0.4;
        console.log(document.getElementById('tagd').style.opacity);


function frame()
    {
            num = 0.1;
            elem.style.opacity += num;

    }


}

setInterval 第二次 opacity 不变! 接缝,我不能不止一次改变不透明度..

html/css 代码如下:

<html>

<style>
#tagd{
width: 500px;
height: 500px;
background: darkred;
opacity: 0;
}
</style>

<head>
<script src="test.js"></script>
</head>


<body>

<input type="button" onclick="anime()">

<div id="tagd"></div>

</body>

</html>

您可以尝试使用 CSS transitions 而不是 JS。 制作两个 CSS 类 并使用 JS 更改它们。

例如。 CSS:

#tagd {
    opacity: 0;
}


.visible {
    -webkit-transition: opacity 3s ease-in-out;
    -moz-transition: opacity 3s ease-in-out;
    -ms-transition: opacity 3s ease-in-out;
    -o-transition: opacity 3s ease-in-out;
    opacity: 1!important;
}

JS:

function anime() {
    var element = document.getElementById("tagd");
    element.classList.toggle("visible");
}