猿问

如何在图像更改时暂停音频 onmouseout

我有一个图像,当用户将鼠标悬停在图像上时,该图像会更改为新图像。单击新图像后,就会播放音频文件。当用户鼠标移出图像时,图像将恢复为默认图像。问题是音频仍在播放。我不太擅长js,当用户鼠标移出时如何让音频暂停?非常感谢任何有用的反馈。下面是代码。


<script type="text/javascript">

    function setNewImg() {

        document.getElementById("about-me-img").src = "https://storage.googleapis.com/gd-wagtail-prod-assets/images/evolving_google_identity_2x.max-4000x2000.jpegquality-90.jpg";

    }

    function setOldImg() {

        document.getElementById("about-me-img").src = "imgs/about-me.png";


    }

    function pauseAudio() {

        document.getElementById("about-me-img").pause();

    }

</script>


<audio id="audio-play">

    <source src="audio.mp3" type="audio/mpeg" />

    </audio>


    <img id="about-me-img" onmouseover="setNewImg()" onmouseout="setOldImg()" onclick="document.getElementById('audio-play').play(); return false;" class="about-me-image about-me-img" src="imgs/about-me.png" alt="" width="200px;">

javascriptjQueryhtmlCSS


长风秋雁
浏览 76回答 3
3回答

慕村225694

拨打pauseAudio电话setOldImg,然后更改document.getElementById("about-me-img").pause();为document.getElementById("audio-play").pause();function setOldImg() {&nbsp; &nbsp; document.getElementById("about-me-img").src = "imgs/about-me.png";&nbsp; &nbsp; pauseAudio();}function pauseAudio() {&nbsp; &nbsp; document.getElementById("audio-play").pause();}

HUWWW

尝试将 paiseAudio() 函数中的“about-me-img”更改为“audio-play”。

开心每一天1111

要解决此问题,您只需在元素上发生这种情况时调用pause()该元素即可。audiomouseoutimg但是您应该注意,onX事件属性现在已经非常过时,不再是好的做法。您应该以不引人注目的方式附加您的事件。因此,请尝试以下操作:document.addEventListener('DOMContentLoaded', () => {&nbsp; let audio = document.querySelector('#audio-play');&nbsp; let img = document.querySelector('#about-me-img');&nbsp; audio.volume = 0.1; // just for testing, so it doesn't deafen you&nbsp; img.addEventListener('mouseover', () => img.src = 'https://storage.googleapis.com/gd-wagtail-prod-assets/images/evolving_google_identity_2x.max-4000x2000.jpegquality-90.jpg');&nbsp; img.addEventListener('mouseout', () => {&nbsp; &nbsp; img.src = 'imgs/about-me.png';&nbsp; &nbsp; audio.pause();&nbsp; });&nbsp; img.addEventListener('click', () => audio.play());});img {&nbsp; display: block;&nbsp; width: 200px;&nbsp; height: 200px;&nbsp; background-color: #C00;}<audio id="audio-play" controls>&nbsp; <source src="http://www.sousound.com/music/healing/healing_01.mp3" type="audio/mpeg" /></audio><img id="about-me-img" class="about-me-image about-me-img" src="imgs/about-me.png" alt="" />
随时随地看视频慕课网APP

相关分类

Html5
我要回答