使用jQuery的:
$("object_element_id") .on ('mouseover', function(e){
// audio play code here
});
$("object_element_id") .on ('mouseout', function(e){
// audio pause/stop code here
});
为什么 “上”?试想一下“AJAX页面刷新”。对于其删除:
$("object_element_id") .off ('mouseenter');
为什么 “鼠标悬停” 和 “鼠标移开”?也许你想为每个状态添加额外的功能,比如改变按钮的IMG SRC,制作一些效果...感觉自由。为什么“e”元素? E元素是发起事件的对象 - 图像,链接等。用它来做所有事情(或者只是删除它)。
对于音频播放,您可以使用HTML5标签。这很容易通过主流浏览器都支持(你不问“retrocompatibility”),您可以缓存元素(如Mateusz的回答),并使用它:
var $audio = $("#audio_element_id"); //for cache the element
$audio.setAttribute('src', url_link); //for change the URL file (ir can be MP3, OGG...)
$audio.play(); //for the mouseover
$audio.stop(); //for the mouseout
然后,最终代码:
var $audio = $("audio_element"); //caching
$("object_element_id") .on ('mouseover', function(e){
$audio.play();
});
$("object_element_id") .on ('mouseout', function(e){
$audio.stop();
});