innerHTML会导致Chrome中不需要的滚动 [英] innerHTML causes unwanted scroll in Chrome

查看:97
本文介绍了innerHTML会导致Chrome中不需要的滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的设置:点击图片后,我想播放一个mp3文件。

I have a simple set up: upon clicking an image, I want an mp3 file to play.

从我记得的大多数来源,建议创建一个虚拟的span元素,人们可以在点击图像时将音频播放器嵌入到自动启动中。

From most sources that I recall, the recommendation is to create a dummy span element where one can embed an audio player to auto start upon clicking the image.

以下是执行此类操作的功能:

Here's the function to perform such an action:

<script language="javascript" type="text/javascript">
  function playSound(soundfile,evt) {
    document.getElementById("dummy").innerHTML = "<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
    evt.preventDefault(); // this doesnt do anything
    return false; // neither does this
  }
</script>

图片的HTML代码:

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

我将虚拟跨度放在页面的最底部。单击图像后,声音会播放,但令人难以置信的烦恼是页面会自动向下滚动到此span元素的位置。

I placed the "dummy" span at the very bottom of the page. Upon clicking the image, the sound plays, but the incredibly annoying thing is that the page automatically scrolls down to the location of this span element.

我试过这个IE和Firefox:不会出现此问题。只有在最新版本的Chrome(24.0.1312.56米)中才会发生这种情况。我在两台电脑上试过这个。

I've tried this on IE and Firefox: this problem doesn't occur. It's only in the most recent version of Chrome (24.0.1312.56 m) that this happens. I have tried this on two computers.

有谁知道怎么了?你怎么摆脱这个恼人的卷轴?

Does anyone know what's up? How do you get rid of this annoying scroll?

返回false; 没有帮助(两者都没有;第二个只通过属性滚动到顶部。 preventDefault()也不是。也没有将 href 属性从更改为 javascript:void(0)

The return false; doesn't help (neither of them; the second one just presents scrolling to the top via the # attribute). Neither does the preventDefault(). Neither does changing the a href attribute from # to javascript:void(0).

推荐答案

而不是使用虚拟 span 我发现在Javascript中有 play 和<$ c >视频 DOM元素,所以我只是重写代码以避免Chrome错误。显然,IE8或旧版本不支持它,但这是值得的权衡。

Instead of using a dummy span element, I found out that there is a play() method in Javascript for the audio and video DOM elements, so I just rewrote the code to avoid the Chrome bug. Apparently, it's not supported for IE8 or older versions, but it's a worthwhile trade-off.

<audio id="aud">
    <source src="aud.ogg" type="audio/ogg" />
    <source src="aud.mp3" type="audio/mpeg" />
</audio>
<a href="#" onClick="document.getElementById('aud').play(); return false;">
  Link
</a>

这篇关于innerHTML会导致Chrome中不需要的滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆