javascript - 如何正确地将元素滚动到始终有效的视图中?
问题描述
我试过这个
let errorMsgEl = document.querySelector('#myMsgField');
errorMsgEl.scrollIntoView(); //this doesnt work, AND does not scroll well to the element, it puts the top of the element to the top of the screen. UGLYYYYY and unprofessional
let offsetTop = errorMsgEl.offsetTop + errorMsgEl.offsetHeight;
window.scrollTo(0, offsetTop); //this somehow does not work consistently if the element is display: none
let errorMsgEl = document.querySelector('#errormsg');
errorMsgEl.scrollIntoView(); //doesnt work
document.body.scrollTop -= 200;
document.documentElement.scrollTop -= 200;
.outer{
height: 5000px;
padding-top: 2000px;
}
#errormsg{
padding: 20px;
background-color: salmon;
}
#errormsg:empty{
display: none;
}
<div class="outer">
<div id="errormsg"></div>
</div>
解决方案
推荐阅读
- javascript - 如果使用 javascript 按下后退按钮,则警告网络用户
- python - 如何验证另一个变量中的变量
- git - 如何将 TFVC (2008)(包括历史)上的所有内容转移到 Git 并最终转移到 GitHub?
- reactjs - react-router-dom 和 Typescript:需要类型注释。ts(2742)
- python - 在带有 python 的 Mac OS 上,如何仅列出可写卷?
- spring-boot - 如何在 Spring Boot 的 json 日志中记录未捕获的异常?
- .net-core - Swashbuckle 5.0 - “PathItem”的等价物
- groovy - 在 Groovy 中 - 如何迭代列表中的版本?
- javascript - 使用 Hermes 引擎测量性能
- html - 通过缩小窗口来保持绝对元素的位置