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

时间:2013-12-09 00:15:00

标签: javascript

我需要在英语测量中显示一个充满尺寸和重量的DIV,并且有一个链接允许用户切换到隐藏的DIV,而不是显示Metric。尝试下面的标记,但它不起作用。它拒绝切换。我已经对第一个div进行了测试,没有任何风格和风格'"显示:块;"并且都不起作用。我错过了什么?

<!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>

2 个答案:

答案 0 :(得分:2)

试试这个if语句:

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

答案 1 :(得分:0)

搞定了。我以为我会发布解决方案:

<!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>