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

时间:2019-07-08 10:44:00

标签: javascript css opacity

我希望我的<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>

1 个答案:

答案 0 :(得分:1)

您可以尝试使用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");
}