stopPropagation()不适用于Firefox中的音频元素

时间:2014-01-10 19:17:25

标签: jquery html5 html5-audio stoppropagation

我在锚标记中嵌入了HTML5音频元素。我知道它有点奇怪,但它在我的具体用例中确实很有意义。

enter image description here

我遇到的问题是,每当我点击播放按钮时,也会在父元素上触发点击事件,转到google.com

我通过使用jQuery停止事件传播来解决大多数浏览器的问题:

$('audio').click(function(e) { e.stopPropagation(); });

这在IE和谷歌浏览器中运行良好。但它在Firefox中失败了。在Safari中,当我单击播放按钮时它可以工作,但是如果我更改音量,也会在父元素上触发click事件。

还知道如何在Firefox和Safari中使用它吗?

FIDDLE

3 个答案:

答案 0 :(得分:1)

我认为如果你从事件处理程序中return false;那么这似乎取消了chrome中的click事件。见这里:http://jsfiddle.net/dLKD4/1/

答案 1 :(得分:1)

您应该使用有效的HTML。无论如何,这应该在FF(和所有浏览器)中修复你的问题:

jsFiddle

$('audio').click(function (e) {
    var $a = $(this).closest('a');
    $a.data('href', $a.attr('href')).removeAttr('href');
}).on('mouseleave', function () {
    var $a = $(this).closest('a');
    $a.attr('href', $a.data('href'));
});

答案 2 :(得分:1)

这适用于Firefox(这里是jsfiddle):

<div class="audio-container">
    <p>You can click this entire box, and it will take you too http://google.com</p>
    <audio controls>
        <source src="http://www.freetone.me/ring/Root/Music/Adventure_Time_Wedding_bells_8bit.mp3" type="audio/mpeg">
        Your browser does not support the audio element.
    </audio>
    <p>However, I would very much like to prevent this box's default click behaviour if a click is performed on the audio element...</p>
</div>

$('audio').click(function(e) { e.stopPropagation(); });

$('div').click(function(e) {
    window.open("http://www.google.com/","_blank");
});

正如您所看到的,一个小小的变化是将 a 标记更改为 div 标记。不知道为什么,但也许 stopPropagation 方法由于与内联元素中的块级元素等有关而起作用。

当您将最高级别的祖先(在本例中为 a )更改为块级元素(在本例中为 div )时,它似乎可以正常工作很好。