如何在不将用户发送到页面顶部的情况下触发 javascript playsound 事件 onclick?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8556203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I fire a javascript playsound event onclick without sending the user to the top of the page?
提问by JD2011
I have the following code on a page on my site — when the user clicks on the image a sound plays:
我在我网站的一个页面上有以下代码——当用户点击图像时会播放声音:
<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>
It all works great, but the image is at the bottom of the page, and when the user clicks the image they are redirected back to the top of the page. Is there any way to get this working so that there is only an audio change, and not a visual one (if that makes sense!)?
一切都很好,但图像位于页面底部,当用户单击图像时,它们会被重定向回页面顶部。有什么方法可以让这个工作,以便只有音频变化,而不是视觉变化(如果有道理!)?
When using a mouseover function instead, such as
当使用鼠标悬停功能时,例如
<a onmouseover="playSound('sound.mp3');"><img src="image.png" /></a>
the user remains where they were on the page, but I would like them to have the option of playing the sound on click and not on rollover.
用户保持在页面上的位置,但我希望他们可以选择在点击时播放声音而不是在鼠标悬停时播放。
回答by Grexis
The problem is your href attribute. # as an anchor sends it to the top of the page. Use
问题是你的 href 属性。# 作为锚将其发送到页面顶部。用
<a href="javascript: void(0);" onclick="playSound('sound.mp3');">...</a>
Also, always include an href attribute to links.
此外,始终在链接中包含 href 属性。
回答by Alejandro Iván
You can (and I think is more correct in cases where Javascript support is limited), to use a link like:
您可以(我认为在 Javascript 支持有限的情况下更正确),使用如下链接:
<a href="#" onclick="playSound('sound.mp3'); return false;">...</a>
instead of Grexis one, because if the browser you're using doesn't support Js, then the "onclick" event will never be fired and thus Js won't be read. It won't be a problem, probably, but still you should consider using better coding techniques.
而不是 Grexis 一个,因为如果您使用的浏览器不支持 Js,那么“onclick”事件将永远不会被触发,因此 Js 将不会被读取。这可能不是问题,但您仍然应该考虑使用更好的编码技术。
回答by KSA
instead of having the onclick event in an a tag, get rid of it and put it on the img tag. if you like the cursor for links, you can change the style too.
不要将 onclick 事件放在 a 标签中,而是将其删除并将其放在 img 标签上。如果您喜欢链接的光标,您也可以更改样式。
Example code has been indented so it actually shows in the post.
示例代码已缩进,因此它实际上显示在帖子中。
<img src="image.png" style="cursor:pointer;" onclick="playSound ('sound.mp3')" />