【问题标题】:How to stop event propagation in IE8如何在 IE8 中停止事件传播
【发布时间】:2015-10-12 06:04:01
【问题描述】:

嗯,我知道这个问题或类似的问题已经被问过很多次了。但是通读它们我仍然无法解决问题。

我有以下代码

    $('div#ItemCollection').on('click', function () {

        if ($('div#ListContainer').is(":visible")) {
            $('div#ListContainer').slideUp(400);
        }
        else {
            $('div#ListContainer').slideDown(400)
        }

     //What I have to write here to prevent event propagation
     //in IE8. Cause event.stopPropagation() does not work on IE8.
     //And which is also work on other browsers.
    })

$('body').click(function () {

    if ($('div#ListContainer').is(":visible")) {
        $('div#ListContainer').slideUp(400);
    }
    //Here as well
})

当我点击它的一侧时,我使用$('body').click(function () {}) 事件向上滑动div#ListContainer。因为event.stopPropagation() 在 Internet Explorer 8 中不起作用,div 只是打开和关闭。

【问题讨论】:

  • "event.stopPropagation()" 适用于 IE8,您的代码有问题。创建一个演示,然后有人可能会提供帮助。否则,您当前问题的答案是“为了防止事件冒泡 - 使用 event.stopPropagation()”。
  • @dfsq:澄清一下,"event.stopPropagation()" 仅在 event 对象是 jQuery 对象时在 IE8 中有效。普通的 Javascript "event.stopPropagation()" 仅适用于 IE9+。文档:stopPropagation

标签: javascript jquery internet-explorer-8


【解决方案1】:

在事件处理函数中使用事件参数再试一次,例如

$('body').click(function (event) { ...

如果event.stopPropagation() 未定义,您可以使用仅限IE 的属性cancelBubble 来防止事件移动到下一个目标。注意,cancelBubble 已弃用,仅用于 IE8 及更早版本:

if(event.stopPropagation)
    event.stopPropagation();
else
    event.cancelBubble=true;

请查看this questionMSDN documentation

【讨论】:

  • 是的,cancelBubble 有效。现在是 2019 年,是的,还有地方在使用 IE7。
【解决方案2】:

将您的代码更改为:

$('div#ItemCollection').on('click', function (e) { // add e var here
    if ($('div#ListContainer').is(":visible")) {
        $('div#ListContainer').slideUp(400);
    }
    else {
        $('div#ListContainer').slideDown(400)
    }
    e.stopPropagation(); // e is a jQuery object that does magic to work in IE8
})

$('body').click(function () {
    if ($('div#ListContainer').is(":visible")) {
        $('div#ListContainer').slideUp(400);
    }
    // Nothing needed here
})

请注意,event.stopPropagation() 仅在 event 对象是 jQuery 对象时才在 IE8 中有效。普通的 Javascript event.stopPropagation() 仅适用于 IE9+。

【讨论】:

    猜你喜欢
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    • 2017-11-18
    相关资源
    最近更新 更多