首页 > 解决方案 > 如何防止自动滚动到重点内容可编辑的 div?

问题描述

input并且textarea像我想要的那样工作,但contentEditable工作方式不同:当页面滚动时,contentEditable焦点和新元素在contentEditable浏览器自动移动滚动之前添加。

如何预防?为什么会这样?

例子:在此处输入图像描述

setInterval(()=> {
  const div = document.createElement('div');
  div.className = "item";
  document.querySelector('.items').appendChild(div);
}, 1000);

window.scrollTo(0, 10);
document.querySelector('div[contentEditable]').focus();
.scroll {
  height: 2000px;
}

.item {
  height: 20px;
  background: red;
  margin-bottom: 2px;
  width: 100px;
}
<div class="scroll">
  <div class="items">
    <div class="item"></div>
  </div>
  <div><div contentEditable="true">Put focus here (ContentEditable)</div></div>
  <div><input type="text" value="Input type text"></div>
  <div><textarea>TextArea</textarea></div>
</div>

PS macOS Safari 像我想要的那样工作,Chrome/FireFox 重复这种情况。

标签: javascripthtmlcss

解决方案


推荐阅读