首页 > 解决方案 > 如何正确地将元素滚动到始终有效的视图中?

问题描述

我试过这个

                        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>

标签: javascriptscroll

解决方案


推荐阅读