簡體   English   中英

嘗試在mouseover事件上播放HTML5音頻

[英]Trying to play HTML5 audio on a mouseover event

我不確定為什么這個腳本不能工作,因為我應該思考它,當我運行它時不會發生錯誤。 如果此腳本的交互方式有任何不同,我也正在運行qTip 2。

這是我的腳本。

JS

    <script type="text/javascript">
var $j = jQuery.noConflict();

var growlSound = $j("#growlSound")[0];
$j("#growl")
    .mouseenter(function() {
            growlSound.play();
    });

var laughSound = $j("#laughSound")[0];
$j("#laugh")
    .mouseenter(function() {
            laughSound.play();
    });

</script>

HTML

<audio id="growlSound" preload="auto">
                            <source src="/messages4u/2011/images/october/growl.ogg">
                            <source src="/messages4u/2011/images/october/growl.mp3">
                            Your browser does not support HTML5 Audio. Please Upgrade Your Browser.
                    </audio>
                            <audio id="laughSound" preload="auto">
                            <source src="/messages4u/2011/images/october/laugh.ogg">
                            <source src="/messages4u/2011/images/october/laugh.mp3">
                            Your browser does not support HTML5 Audio. Please Upgrade Your Browser.
                    </audio>
    <p><img src="/messages4u/2011/images/october/halloween4.jpg" width="600" border="0" usemap="#Map" class="center" style="width: 600px;" />
      <map name="Map" id="Map">
        <area class="growl" id="growl" style="cursor:default;" shape="rect" coords="117,118,225,223" href="#" />
        <area class="laugh" id="laugh" style="cursor:default;" shape="rect" coords="255,244,308,292" href="#" />
      </map>
</p>

正如您所看到的,我試圖在mouseover事件上播放音頻。 我無法使它正常工作,但是我不確定錯誤在哪里。

更新 - 似乎mouseenter事件無效。

可能還有其他因素在起作用。 我在這里創建了一個更簡單的示例。 似乎可以正常工作(在Chrome中):

http://jsfiddle.net/5PnCt/2/

可能是:

  • 您的音頻文件未正確鏈接
  • 您以某種方式無法觸發mouseenter事件
  • 您沒有正確綁定事件

要測試第二種情況,請添加以下內容:

        console.log('playing');

...給您的其中一個mouseenter處理程序。 如果事件被觸發,您應該看到日志消息。

對於第三種情況,請確保將腳本放在它們影響的HTML之后,或者使用以下包裝器確保它們在HTML加載之前不執行:

var $j = jQuery.noConflict();
$j(document).ready(function(){
    ...code goes here...
});

如果頁面上不存在事件,則不能選擇事件並將其綁定到元素,因此代碼的順序很重要。 使用document.ready是解決此問題的一種方法。 它告訴jQuery在嘗試執行腳本之前等待頁面完全加載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM