需要切换2个DIV的DIV可见性

Need to Toggle DIV Visibility for 2 DIVs

本文关键字:DIV 可见性 2个      更新时间:2024-05-27

我需要用英制度量显示一个充满维度和权重的div,并有一个链接允许用户切换到一个隐藏的div(显示公制)。正在尝试下面的标记,但它不起作用。它拒绝切换。我测试了第一个没有样式的div和它的样式"display:block;",两者都不起作用。我错过了什么?

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <style type="text/css">
    <!--
    body {
      color:#000000;
      background-color:#FFFFFF;
    }
    a  { color:#0000FF; }
    a:visited { color:#800080; }
    a:hover { color:#008000; }
    a:active { color:#FF0000; }
    -->
    </style>
    <!--[if IE]>
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <script type="text/javascript">
    function toggle_visibility(eng, met) {
        var e1 = document.getElementById(eng);
        var e2 = document.getElementById(met);
        if(e1.style.display == 'block')
            e1.style.display = 'none';
            e2.style.display = 'block';
        else
            e1.style.display = 'block';
            e2.style.display = 'none';
    }
    </script>
  </head>
  <body>
    <div id="eng" style="display: block;">
      This is English<br />
      <a href="#" onclick="toggle_visibility('eng','met');">Convert to Metric</a>
    </div>
    <div id="met" style="display: none;">
      This is Metric<br />
      <a href="#" onclick="toggle_visibility('met','eng');">Convert to English</a>
    </div>
  </body>
</html>

试试这个if语句:

    if(e1.style.display == 'block') {
        e1.style.display = 'none';
        e2.style.display = 'block';
    } else {
        e1.style.display = 'block';
        e2.style.display = 'none';
    }

工作正常。我想我应该发布解决方案:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <style type="text/css">
    <!--
    body {
      color:#000000;
      background-color:#FFFFFF;
    }
    a  { color:#0000FF; }
    a:visited { color:#800080; }
    a:hover { color:#008000; }
    a:active { color:#FF0000; }
    -->
    </style>
    <!--[if IE]>
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <script type="text/javascript">
    function toggle_visibility() {
      var e1 = document.getElementById("eng");
      var e2 = document.getElementById("met");
      if(e1.style.display == 'block') {
        e1.style.display = 'none';
        e2.style.display = 'block';
      }
      else {
        e1.style.display = 'block';
        e2.style.display = 'none';
      } 
    }
    </script>
  </head>
  <body>
    <div id="eng" style="display: block;">
      This is English<br />
      <a href="#" onclick="toggle_visibility();">Convert to Metric</a>
    </div>
    <div id="met" style="display: none;">
      This is Metric<br />
      <a href="#" onclick="toggle_visibility();">Convert to English</a>
    </div>
  </body>
</html>