如何在不将用户发送到页面顶部的情况下触发一个javascript playsound事件onclick?

如何在不将用户发送到页面顶部的情况下触发一个javascript playsound事件onclick?,javascript,onclick,Javascript,Onclick,我的网站页面上有以下代码-当用户单击声音播放的图像时: <script language="javascript" type="text/javascript"> function playSound(soundfile) { document.getElementById("dummy").innerHTML= "<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\"

我的网站页面上有以下代码-当用户单击声音播放的图像时:

<script language="javascript" type="text/javascript">
 function playSound(soundfile) {
 document.getElementById("dummy").innerHTML=
 "<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
 }
 </script>
 <span id="dummy"></span>
 <div id="soundimage">
 <a href="#" onclick="playSound('sound.mp3');"><img src="image.png" /></a>
 </div>

功能播放声音(声音文件){
document.getElementById(“dummy”).innerHTML=
"";
}
这一切都很好,但图像位于页面底部,当用户单击图像时,它们会重定向回页面顶部。有没有办法让它工作起来,这样就只有音频变化,而不是视频变化(如果有意义的话!)

当使用鼠标悬停功能时,例如

<a onmouseover="playSound('sound.mp3');"><img src="image.png" /></a>


用户仍保留在页面上的位置,但我希望他们可以选择单击而不是滚动播放声音。

问题在于href属性。#当锚发送到页面顶部时。使用

<a href="javascript: void(0);" onclick="playSound('sound.mp3');">...</a>

另外,始终在链接中包含href属性。

您可以(我认为在Javascript支持有限的情况下更正确)使用如下链接:

<a href="#" onclick="playSound('sound.mp3'); return false;">...</a>


而不是Grexis one,因为如果您使用的浏览器不支持Js,那么“onclick”事件将永远不会被触发,因此Js将不会被读取。这可能不是问题,但你还是应该考虑使用更好的编码技术。

而不是在一个标签中拥有OnCutter事件,把它删除并放到IMG标签上。如果您喜欢链接的光标,也可以更改样式

示例代码已经缩进,因此它实际显示在文章中

<img src="image.png" style="cursor:pointer;" onclick="playSound ('sound.mp3')" />


同意,这种方法可能会奏效。但是,内联javascript通常不受欢迎。也只能使用href=“javascript:;”;)你能考虑通过给你的解决方案添加一些样本代码来改进你的答案吗?