简体   繁体   中英

Audio when hover over an image

I am trying to play multiple audio files when the viewer hovers over different images, and I do not wish any of the player/bar/function to be shown on the screen, I just want the viewer to hover over the image, and the sound plays, it will finish playing even if the user moved the cursor away. All my images are being placed in apDiv tags

$(function(){
    $('#apDiv3').hover(
    function() { $("killyou")[0].play(); },
    function() { $("killyou")[0].pause(); }
    )
});


<audio id="killyou" controls preload="auto">
    <source src="iwilkillyou.mp3" type="audio/mpeg"></source>
    <div id="apDiv3">
        <img src="explosion_by_dbszabo1-d3hmssu.png" width="175" height="5">
    </div>
</audio>

I got this to work when hovering, it plays the sound, but I cant use it for multiple images, and the sound stops when the mouse is moved away from the image, it's my first time using html and JQuery, anyone can help me out with this? Thank you!

(edit: re-read your question)

Perhaps:

$('.audio-source img').mouseover(function() {
    $('player source').attr('src', $(this).data('file'))
            .parent()[0].play();
});

With HTML:

<audio hidden id="player" controls preload="auto">
    <source src="default-audio.mp3" type="audio/mpeg"></source>
</audio>
<div class="audio-source">
    <img data-file="foo.mp3" src="image-1.png"/>
    <img data-file="bar.mp3" src="image-2.png"/>
    <img data-file="baz.mp3" src="image-3.png"/>
</div>

I'm currently unable to test that, though.

The jQuery function .hover(on, off) binds two functions, one for mouse over, one for mouse off. All you need is mouse on, so you can use the function .mouseover(function) . What the jQuery snippet does is grab the data-file attribute from the image you hover over, and apply it to the src attribute of the <source> tag. Then we grab the parent, which is the <audio> tag, and call play() on the DOM node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM