【问题标题】:Why does the javascript I used to show/hide divs not work in IE?为什么我用来显示/隐藏 div 的 javascript 在 IE 中不起作用?
【发布时间】:2021-03-02 15:19:31
【问题描述】:

我修改了我在 @dinindu 发布的 stackoverflow 上找到的一个脚本,该脚本似乎可以在除 IE 之外的所有浏览器上完美运行,但不幸的是,我们确实有客户端仍在使用 IE。有关 IE 解决方法的任何想法?

我是一名技术作家,不懂 javascript,所以请多多包涵。

这是我项目中的脚本:

function toggle_visibility(id) {
    const target = document.getElementById(id);
    if (!target) return;

    // Hide all other div elements.
    const divs = document.querySelectorAll('.div');
    for (const div of divs) {
    div.style.display = 'none';
}

  // Show selected one
target.style.display = 'block';
}
<div id="intro" class="div">
    <img src="../../Resources/Images/101-intro.jpg" title="Inventory Cycle" usemap="#map1" />
    <map id="map1">
        <area shape="rectangle" coords="480,506,564,522" dragDirection="0" href="#" onclick="toggle_visibility('transfer');" />
        <area shape="rectangle" coords="628,288,738,304" dragDirection="0" href="#" onclick="toggle_visibility('receive');" />
    </map>
</div>
<div id="transfer" class="div" style="display: none;">
    <img src="../../Resources/Images/101-transfer.jpg" title="Transfer" usemap="#map2" />
    <map id="map2">
        <area shape="circle" coords="961,36,15" dragDirection="0" alt="Back" href="#" onclick="toggle_visibility('intro');" />
    </map>
</div>
<div id="receive" class="div" style="display: none;">
    <img src="../../Resources/Images/101-receive.jpg" title="Supplier" usemap="#map3" />
    <map id="map3">
        <area shape="circle" coords="961,36,15" dragDirection="0" alt="Back" href="#" onclick="toggle_visibility('intro');" />
    </map>
</div>

代码基本上只显示101-intro.jpg。单击图像的特定部分会隐藏图像并显示其他两个图像之一(101-transfer.jpg 或 101-receive.jpg)。点击右上角的 101-transfer.jpg 或 101-receive.jpg 将其隐藏并再次显示 101-intro.jpg。

【问题讨论】:

    标签: javascript html show-hide


    【解决方案1】:

    您的脚本使用 IE11 或更低版本中不可用的 ES6 (EcmaScript 2015) 功能。 我已经重写了你的函数以使用下面的旧 Javascript 版本,这应该在 IE11 中工作。

    function toggle_visibility(id) {
        var target = document.getElementById(id);
        if (!target) return;
    
        // Hide all other div elements.
        var divs = document.getElementsByClassName('div');
        for (var i = 0; i < divs.length; i++) {
            divs[i].style.display = 'none';
        }
    
        // Show selected one
        target.style.display = 'block';
    }
    

    一般情况下,你可以使用 babel 之类的工具将 ES6+ 代码转译成 IE11 兼容的 ES5 代码。

    另外,如果以后出现这样的事情,你可以使用在线的 babel 转译器,例如babeljs.io/repl,在这里你也可以转换代码,而不需要自己知道如何转译。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 1970-01-01
      • 2012-04-20
      • 2018-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多