Prevent div from scrolling to top when inner div i

2019-06-24 10:52发布

问题:

I have an outer div with style.overflow set to auto. It contains a larger child div which causes the outer div to become scrollable.

When the outer div is scrolled to the bottom, giving focus to the inner div causes the scroll position to return to top left (0,0). This happens only on IE 11. A working example of the issue is provided through the link below (the div is given focus when clicked)

https://jsfiddle.net/wy6u8b76/6/

Is there a way to prevent the window from scrolling to the top?

回答1:

I was able to work around this by pre-setting the scrollTop to 0, and then moving the margin so it remains in the same location. Finally you can undo all of this insanity.

Here's your modified example: https://jsfiddle.net/2n1f25nk/1/

document.getElementById('div1').onclick = function() {
  var div1 = document.getElementById('div1');
  var div2 = document.getElementById('div2');
  var scrollTop = div1.scrollTop;
  div2.style.marginTop = (-scrollTop) + 'px';
  div1.scrollTop = 0;
  // give focus to inner div
  document.getElementById('div2').focus();
  // Undo the horribleness
  div2.style.marginTop = '0px';
  div1.scrollTop = scrollTop;
}