How do I fire a javascript playsound event onclick without sending the user to the top of the page?(如何在不将用户发送到页面顶部的情况下触发 javascript playsound 事件 onclick?)
问题描述
我的网站页面上有以下代码——当用户点击图片时,会播放声音:
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.
推荐答案
问题是你的 href 属性.# 作为锚点将其发送到页面顶部.使用
The problem is your href attribute. # as an anchor sends it to the top of the page. Use
<a href="javascript: void(0);" onclick="playSound('sound.mp3');">...</a>
此外,始终在链接中包含 href 属性.
Also, always include an href attribute to links.
这篇关于如何在不将用户发送到页面顶部的情况下触发 javascript playsound 事件 onclick?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不将用户发送到页面顶部的情况下触发


基础教程推荐
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01