首页 > 解决方案 > 在IE中找不到切换LI元素的解决方案,其他浏览器都可以

问题描述

(function() {
  window.onload = function() {
    document.getElementById("checking").onclick = function() {
      document.getElementById("knoz").style.display = !this.checked ? null : "none";
      document.getElementById("acces").style.display = this.checked ? null : "none";
    };
  };
})();
.selector ul li {
  list-style: none;
  float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<input type="checkbox" id="checking">check me
<div class="selector">
  <ul>
    <li id="knoz" name="knoz">element knoz</li>
    <li id="acces" name="acces" style="display:none">element acces</li>
  </ul>
</div>

当复选框 id=checking 被选中时,此函数会切换出 2 个 LI 元素。它可以在除 Internet Explorer 之外的所有其他浏览器中完美运行。

1 Li 元素有 style="display: none;" 另一个有 style="display: block;"

 (function() {
    window.onload = function() {
      document.getElementById("checking").onclick = function() {
        document.getElementById("knoz").style.display = !this.checked ? null : "none";
        document.getElementById("acces").style.display = this.checked ? null : "none";
      };
    };
  })();

对于所有浏览器,代码完美地切换了 2 个 LI 元素。在 IE 中,它隐藏了初始的 LI,但不显示替换的 LI。取消勾选复选框什么都不做。这两个元素都保持隐藏状态。

标签: functioninternet-explorerswitch-statementhtml-lists

解决方案


尝试如下修改您的代码(将“null”更改为“block”):

<script>
    (function () {
        window.onload = function () {
            document.getElementById("checking").onclick = function () {
                document.getElementById("knoz").style.display = !this.checked ? "block" : "none";
                document.getElementById("acces").style.display = this.checked ? "block" : "none";
            };
        };
    })();
</script>

然后,在 IE 浏览器中的结果如下:

在此处输入图像描述


推荐阅读