调用Js函数onMouseOver

时间:2014-04-18 14:32:42

标签: javascript html onmouseover

有没有办法在HTML中用鼠标调用Javascript函数?

我有以下代码:

<script src="navSound.js" type="text/javascript"></script>

<a href="#" onmouseover="bubble2.playclip()"><li class="navBackground"><div class="navButton">Gallery</div></li></a>

我希望它调用名为“playclip()”的函数,该函数位于链接到名为navSound.js的HTML文档的外部文件中

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

是的,有可能这样:

<html>
<head>

<script type='text/javascript'>

function playclip() {
    alert('playing clip...');
}

</script>

</head>
<body>

<a href="#" onmouseover="playclip()"><li class="navBackground"><div class="navButton">Gallery</div></li></a>

</body>
</html>

在您的情况下,playclip()函数将使用'src'属性包含在脚本标记中包含的外部文件“navSound.js”中。

<强>更新

我更新了你的小提琴,你可以看到这里的改变效果很好:

http://jsfiddle.net/Lb966/(小心:你会听到一匹马的neiggggggghhhhhhhhhhhhhhh;)

我也粘贴下面的标记+代码:

<html>
<head>
<script type='text/javascript'>

window.onload = function() {

    var html5_audiotypes={ //define list of audio file extensions and their associated audio types. Add to it if your specified audio file isn't on this list:
        "mp3": "audio/mpeg",
        "mp4": "audio/mp4",
        "ogg": "audio/ogg",
        "wav": "audio/wav"
    }

    function createsoundbite(sound){
        var html5audio=document.createElement('audio');
        if (html5audio.canPlayType){ //check support for HTML5 audio
            for (var i=0; i<arguments.length; i++){
                var sourceel=document.createElement('source')
                sourceel.setAttribute('src', arguments[i])
                if (arguments[i].match(/\.(\w+)$/i))
                    sourceel.setAttribute('type', html5_audiotypes[RegExp.$1])
                html5audio.appendChild(sourceel)
            }
            html5audio.load()
            html5audio.playclip=function(){
                //html5audio.pause()
                html5audio.currentTime=0
                html5audio.play()
            }
            return html5audio
        }
        else{
            return {playclip:function(){throw new Error("Your browser doesn't support HTML5 audio unfortunately")}}
        }
    }

    var audio = createsoundbite("http://www.w3schools.com/html/horse.ogg");
    audio.setAttribute('id', 'myAudio');
    document.getElementById('content').appendChild(audio);

}

</script>
</head>
<body>
<div id='content'></div>
<a href="#" onmouseover="document.getElementById('myAudio').play()">Gallery</a>
</body>
</html>