JS:鼠标悬停时播放剪辑

时间:2018-03-17 15:01:01

标签: javascript html html5-audio

我想在鼠标悬停时触发剪辑但它不起作用。我可以登录控制台,但看起来我做错了播放剪辑......这是什么?

window.onload = function() {
    var clip1 = document.getElementById("clip1");
    var projects = document.getElementById("projects");

    function playClip1() {
        clip1.play();
        console.log("I should play clip1 now");
    }

    projects.addEventListener("mouseover", playClip1);
}
</script>
</head>

<body>
   <audio id="clip1" src="clip1.wav"></audio>
   <a id="projects" href="index.html"> projects </a>
</body>

2 个答案:

答案 0 :(得分:2)

您的代码应该有效,但您可以通过使用承诺获得有关进展情况的更多信息。

以下代码将在两种情况下都记录消息:成功或错误。错误消息可能对您有用。

&#13;
&#13;
window.onload = function() {

  var clip1 = document.getElementById("clip1");
  var projects = document.getElementById("projects");

  function playClip1() {
    clip1.play()
    .then(function() {
        console.log('success');
    })
    .catch(function(error) {
        console.log('error', error);
    });
    console.log("I should play clip1 now");
  }
  projects.addEventListener("mouseover", playClip1);
}
&#13;
<body>
  <audio id="clip1" src="http://www.pacdv.com/sounds/voices/dinner-is-served.wav"></audio>
  <a id="projects" href="index.html"> projects </a>
</body>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

可能是您的console.log()音频文件在路径上丢失,或者在悬停时加载/播放音频文件时出现问题。我尝试过维基媒体的另一个音频文件,它工作正常。我已经添加了一条额外的 window.onload = function(){ var clip1 = document.getElementById("clip1"); var projects = document.getElementById("projects"); function playClip1() { console.log('project link hovered'); clip1.play(); console.log("I should play clip1 now"); } projects.addEventListener("mouseover", playClip1); }消息来检查它是否在悬停时显示消息。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>

<audio id="clip1" src="http://upload.wikimedia.org/wikipedia/commons/6/6f/Cello_Live_Performance_John_Michel_Tchaikovsky_Violin_Concerto_3rd_MVT_applaused_cut.ogg"></audio>
<a id="projects" href="index.html"> projects </a>
</body>
   </html>
sort()

请参阅演示:https://jsbin.com/dijediduzu/edit?html,js,output