如何阻止向contenteditable div插入文本时自动滚动?(仅Chrome存在)
阻止Chrome中contenteditable元素高度扩展时的自动滚动行为
此问题仅在Chrome浏览器中存在。
当向高度向上扩展的contenteditable div中输入文本时,浏览器会自动向上滚动,这种行为导致了糟糕的用户体验,如何阻止该滚动行为?
复现步骤
- 向下滚动页面
- 在包含Insert text的
#bottom-child元素中输入文本直至换行,滚动条会自动上移 - 运行代码片段后选择全屏模式更易复现此问题
复现代码
#parent { height: 2000px; } #container { margin-top: 100px; display: flex; flex-direction: column; height: 200px; width: 200px; background-color: yellow; } #top-child { flex: 1; } #bottom-child { align-self: flex-end; width: 100%; }
<div id="parent"> Please scroll down a little bit and type in text in the 'Insert text' area to see the automatic scroll. <div id="container"> <div id="top-child"></div> <div id="bottom-child" contenteditable="true">Insert text</div> </div> </div>
解决方案
方法1:监听输入事件,手动维持滚动位置
通过监听contenteditable元素的input事件,在元素高度变化前后固定滚动位置:
const bottomChild = document.getElementById('bottom-child'); let currentScrollTop; bottomChild.addEventListener('input', () => { // 记录当前滚动位置 currentScrollTop = window.pageYOffset || document.documentElement.scrollTop; // 等待DOM更新后恢复滚动位置 requestAnimationFrame(() => { window.scrollTo(0, currentScrollTop); }); });
方法2:调整CSS布局,从根源避免向上扩展
修改容器布局,让contenteditable元素向下扩展而非向上,彻底消除触发自动滚动的条件:
#container { margin-top: 100px; display: flex; flex-direction: column; height: 200px; width: 200px; background-color: yellow; justify-content: flex-end; /* 新增:让子元素靠底部排列 */ } #bottom-child { width: 100%; /* 移除align-self: flex-end; */ }
这种纯CSS方案无需额外脚本,通过布局调整让元素向下扩展,自然不会触发浏览器的自动向上滚动。
内容的提问来源于stack exchange,提问作者Ovidijus Parsiunas
相关产品推荐
相关产品推荐

