简体   繁体   English

当内部div被赋予焦点时,防止div滚动到顶部 - IE 11

[英]Prevent div from scrolling to top when inner div is given focus - IE 11

I have an outer div with style.overflow set to auto . 我有一个外部div, style.overflow设置为auto It contains a larger child div which causes the outer div to become scrollable. 它包含一个更大的子div,它使外部div变得可滚动。

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). 当外部div滚动到底部时,将焦点放在内部div会导致滚动位置返回到左上角(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) 这只发生在IE 11上。通过下面的链接提供了该问题的工作示例(点击时div被赋予焦点)

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

Is there a way to prevent the window from scrolling to the top? 有没有办法阻止窗口滚动到顶部?

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. 通过将scrollTop预先设置为0,然后移动边距使其保持在相同位置,我能够解决这个问题。 Finally you can undo all of this insanity. 最后,你可以撤消所有这些精神错乱。

Here's your modified example: https://jsfiddle.net/2n1f25nk/1/ 以下是您修改过的示例: 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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