在悬停图像上播放声音,在悬停时停止

时间:2016-04-26 08:03:57

标签: javascript html onhover audio

我正在尝试实现它,所以当我将鼠标悬停在脉冲图像上方时(我知道它看起来很癌)我希望它播放声音文件,当我从堆叠图像中删除鼠标时,声音文件会停止。

另一件令人兴奋的事情是将图像居中,它们似乎无论如何都将它们定位在角落里,我该如何解决这个问题呢? 目前的代码:似乎无法理解如何做到这一点。

<html>
    <head>
        <title> fagdag 26.04.2016 helårs </title>
            <style>
            #banner {
            vertical-align: middle  
            }
            .pulsate {
            -webkit-animation: pulsate 3s ease-out;
            -webkit-animation-iteration-count: infinite; 
            opacity: 0.5;
            }
            @-webkit-keyframes pulsate {
                    0% { 
                    opacity: 0.5;
                }
                    50% { 
                    opacity: 1.0;
                }
                    100% { 
                    opacity: 0.5;
                }
            }



            </style>
    </head>

    <body>
    <div id="banner">
    <img src="http://i.imgur.com/SrnpgpD.jpg" style="z-index: 0; position: absolute" align="middle"">
    <img class="pulsate" src="http://i.imgur.com/t2Pil1a.png" style="z-index: 1; position: absolute" align="middle""">
    </div>
    <p onmouseover="PlaySound('mySound')" 
    onmouseout="StopSound('mySound')">Hover Over Me To Play</p>
<br><br>
<audio id='mySound' src='http://upload.wikimedia.org/wikipedia/commons/6/6f/Cello_Live_Performance_John_Michel_Tchaikovsky_Violin_Concerto_3rd_MVT_applaused_cut.ogg'/>

    function PlaySound(soundobj) {
    var thissound=document.getElementById(soundobj);
    thissound.play();
}

function StopSound(soundobj) {
    var thissound=document.getElementById(soundobj);
    thissound.pause();
    thissound.currentTime = 0;
}

    </body>
</html>

1 个答案:

答案 0 :(得分:1)

您需要首先添加脚本标记。

要集中对齐文字,您需要使用text-align:center。此外,您应该阅读position:absolute,因为这意味着p标记隐藏在图片后面。

当您将鼠标悬停在图像上时,以下功能将起作用。

&#13;
&#13;
<html>
<head>
  <title>fagdag 26.04.2016 helårs</title>
</head>

<body>
  <div style="text-align:center;" id="banner">
    <img src="http://i.imgur.com/SrnpgpD.jpg" style="z-index: 0;>
    <img src="http://i.imgur.com/t2Pil1a.png" style="z-index: 1; position: relative; text-align:center" class="pulsate">
  </div>
  <p onmouseover="PlaySound( 'mySound') " onmouseout="StopSound( 'mySound') ">Hover Over Me To Play</p>
  <audio id='mySound' src='http://upload.wikimedia.org/wikipedia/commons/6/6f/Cello_Live_Performance_John_Michel_Tchaikovsky_Violin_Concerto_3rd_MVT_applaused_cut.ogg' />

    <script type="text/javascript ">
      function PlaySound(soundobj) {
        var thissound = document.getElementById(soundobj);
        thissound.play();
      }

      function StopSound(soundobj) {
        var thissound = document.getElementById(soundobj);
        thissound.pause();
        thissound.currentTime = 0;
      }
    </script>
</body>
</html>
&#13;
&#13;
&#13;