javascript + 不透明度过渡不起作用

javascript + opacity transition doesn't work

我希望能够通过单击来更改 div 的不透明度。我编写了以下代码,但看起来 opacity: 1s 不起作用,知道为什么吗?

<!DOCTYPE html>
<html>
<head>
    <style> 
        div {
            background-color: red;
            opacity: 0.1;
            filter: Alpha(opacity=50); /* IE8 and earlier */,
            transition: opacity 1s;
        }
    </style>
    <script>
        function changeOpacity() {
            document.getElementById("myDiv").style.opacity = 1;
        }
    </script>
</head>

<body>
    <div id ="myDiv"onclick="changeOpacity()">
        This element's opacity is 0.5! Note that both the text and the background-color are affected by the opacity level!
    </div>
</body>
</html>

希望能帮到你,试试这个:

<!DOCTYPE html>
<html>
<head>
<style> 
    div {
        background-color: red;
        opacity: 0.1;
        filter: Alpha(opacity=50); /* IE8 and earlier */,
        transition: opacity 1s;
    }
</style>
</head>
<body>

<div id ="myDiv"onclick="changeOpacity()">This element's opacity is 0.5! Note that both the text and the background-color are affected by the opacity level!</div>
<script>
    function changeOpacity(){
       document.getElementById("myDiv").style.opacity = 1;
    }
</script>
</body>
</html>