onMouseover change image and play sound, onMouseout reset image back to normal
I'm playing with something in HTML, can I play a sound on mouseover
of an image as well as changing开发者_开发问答 the image while the mouse remains there?
Overall developer view would be great!
Yes, but you will need JavaScript to do a lot of this for you.
For the image, you can have two actions:
<img id="imgID" scr="img/image.jpg" onmouseover="imgover();" onmouseout="imgout();" />
Then your two functions will do what you are looking to do:
imgover () {
document.getElementByID("imgID").scr = "img/newimage.jpg";
//Code to play sound
}
imgout () {
document.getElementByID("imgID").scr = "img/image.jpg";
//Code to stop sound
}
Do you need help with the sound too?
The changing image should be handled with CSS rather than Javascript, and the sound playing should be handled in Javascript.
HTML:
<div class="hover_sound"></div>
CSS:
.hover_sound {
background: url(image.png) no-repeat;
height: 200px;
width: 200px;
}
.hover_sound:hover { url(image_hover.png) no-repeat}
Javascript:
The sound playing should be handled by Javascript, and you can do that with HTML5-compliant browsers that support MP3 (Chrome, Safari, IE9) with the following:
;(function() {
// get the hover element and instantiate sound.
var hoverSoundElement = document.querySelector(".hover_sound")
, sound = new Audio("mysound.mp3")
// play the sound when the mouse enters.
hoverSoundElement.addEventListener("mouseover", sound.play.bind(sound))
hoverSoundElement.addEventListener("mouseout", function() {
// stop the sound when the mouse leaves.
sound.pause()
// reset sound's position to the beginning.
sound.currentTime = 0
})
})()
If you want to support older browsers, then use something like jQuery or MooTools for the DOM stuff and if you want to support older browsers with your sound, use SoundManager2 (http://www.schillmania.com/projects/soundmanager2/) or use multiple audio sources for better support, e.g. OGG and MP3 sources.
The "correct" answer here is right in terms of implementation, but you should try to separate your concerns as much as possible, and switching out an image is a style concern that can easily be handled by CSS instead of Javascript.
精彩评论