简体   繁体   中英

innerHTML causes unwanted scroll in Chrome

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

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>

The HTML code for the image:

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

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.

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?

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) .

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>

Ok I ran into a similar issue and found this but it didn't help me, I figured out a workaround so I decided to post it here to help other people with the same issue. The issue is that the browser figures since this is in response to the user clicking something, it should scroll to show the new html content automatically. The workaround I came up with is like this -

setTimeout(function(){
    document.getElementById('dummy').innerHTML += "THE STUFF";
}, 0);

It simply does a setTimeout for 0 ms and then does the appending of html code, this way it is disassociated with the click event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM