按钮需要点击 2 次才能换出 div

2024-04-21

单击按钮时,我有一个简单的 div 交换。但是,当页面首次加载时,需要用户单击按钮两次才能使该功能起作用。之后一切正常。请问有什么建议吗?

My code:

<script type="text/javascript">
    function SwapDivsWithClick(div1, div2) {
        d1 = document.getElementById(div1);
        d2 = document.getElementById(div2);
        if (d2.style.display == "none") {
            d1.style.display = "none";
            d2.style.display = "block";
        } else {
            d1.style.display = "block";
            d2.style.display = "none";
        }
    }

</script>




<style>
    #swapper-other {
        width: 200px;
        height: 50px;
        background-color: darkred;
        color: #fff;
        display: none;
    }

    #swapper-first {
        width: 200px;
        height: 50px;
        background-color: yellowgreen;
        color: #444;
    }

</style>

 <div id="swapper-first">
    <p>
        <a href="javascript:SwapDivsWithClick('swapper-first','swapper-other')">(Swap Divs)</a>
    </p>


    <p style="margin:0; color:red;">
        This div displayed when the web page first loaded.
    </p>
</div>
<div id="swapper-other">
    <a href="javascript:SwapDivsWithClick('swapper-first','swapper-other')">(Swap Divs)</a>
    <p>
        This div displayed when the link was clicked.
    </p>
</div>

为了检测途中的样式,您应该使用getComputedStyle方法代替。

下面是您的示例的代码更新版本:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <style>
    #swapper-other {
        width: 200px;
        height: 50px;
        background-color: darkred;
        color: #fff;
        display: none;
    }

    #swapper-first {
        width: 200px;
        height: 50px;
        background-color: yellowgreen;
        color: #444;
    }

</style>
  <script type="text/javascript">
    function SwapDivsWithClick(div1, div2, e) {

        let d1 = document.getElementById(div1);
        let d2 = document.getElementById(div2);
        let computedStyleD1 = window.getComputedStyle(d1, null);
        let computedStyleD2 = window.getComputedStyle(d2, null);    
        if (computedStyleD2.display == "none") {             
            d1.style.display = "none";
            d2.style.display = "block";
        } else {
            d1.style.display = "block";
            d2.style.display = "none";
        }

      e.stopPropagation();         
    }

</script>
</head>
<body>
 <div id="swapper-first">
    <p>
        <a href='#' onclick="SwapDivsWithClick('swapper-first','swapper-other', event)">(Swap Divs)</a>
    </p>


    <p style="margin:0; color:red;">
        This div displayed when the web page first loaded.
    </p>
</div>
<div id="swapper-other">
    <a href='#' onclick="SwapDivsWithClick('swapper-first','swapper-other', event)">(Swap Divs)</a>
    <p>
        This div displayed when the link was clicked.
    </p>
</div>
</body>
</html>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

按钮需要点击 2 次才能换出 div 的相关文章

随机推荐