使用 display 属性操作元素

Manipulating elements using the display property

本文关键字:元素 操作 属性 display 使用      更新时间:2023-09-26
<!DOCTYPE html>
<html>
<head>
    <style>
        #myDIV {
            width: 500px;
            height: 500px;
            background-color: lightblue;
            display: none;
        }
        #second {
            width: 500px;
            height: 500px;
            background-color: lightblue;
            display: none;
        }
    </style>
</head>
<body>
    <button onclick="myFunction()">Try it</button>
    <button onclick="myFunction2()">Try this now</button>
    <div id="myDIV">
        This is my DIV element.
    </div>
    <div id="second">
        This is my DIV2 element.
    </div>
    <script>
        function myFunction() {
            document.getElementById("myDIV").style.display = "block";
        }
    </script>
    <script>
        function myFunction2() {
            document.getElementById("second").style.display = "block";
        }
    </script>
</body>
</html>

所以我有这段代码,它将在单击按钮时出现一个div 元素。但是,一旦我单击"第二个"按钮,我希望" myDiv"消失并且"第二"取而代之(确切位置),反之亦然。

请帮忙吗?

<script>
    function myFunction() {
        document.getElementById("myDIV").style.display = "block";
        document.getElementById("second").style.display = "none";
    }
</script>
<script>
    function myFunction2() {
        document.getElementById("second").style.display = "block";
        document.getElementById("myDIV").style.display = "none";
    }
</script>