我试图将页面移动到<div>元素。

我已经尝试了下一个代码无效:

document.getElementById("divFirst").style.visibility = 'visible';
document.getElementById("divFirst").style.display = 'block';

当前回答

下面是一个函数,它可以包含那些固定头的可选偏移量。不需要外部库。

function scrollIntoView(selector, offset = 0) {
  window.scroll(0, document.querySelector(selector).offsetTop - offset);
}

您可以使用JQuery获取元素的高度并滚动到它。

var headerHeight = $('.navbar-fixed-top').height();
scrollIntoView('#some-element', headerHeight)

2018年3月更新

不使用JQuery滚动到这个答案

scrollIntoView('#answer-44786637', document.querySelector('.top-bar').offsetHeight)

其他回答

最好的,最简短的回答是什么即使是动画效果也有效:

var scrollDiv = document.getElementById("myDiv").offsetTop;
window.scrollTo({ top: scrollDiv, behavior: 'smooth'});

如果你有一个固定的导航条,只需从顶部值中减去它的高度,所以如果你的固定导航条高度是70px,第2行将看起来像这样:

window.scrollTo({ top: scrollDiv-70, behavior: 'smooth'});

解释: 第1行获取元素位置 第2行滚动到元素位置;属性添加平滑的动画效果

类似于@穴居人的解决方案

const element = document.getElementById('theelementsid');

if (element) {
    window.scroll({
        top: element.scrollTop,
        behavior: 'smooth',
    }) 
}

scrollIntoView工作良好:

document.getElementById("divFirst").scrollIntoView();

MDN文档中的完整引用: https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView

我们可以通过3种方法来实现:

注意:

"automatic-scroll" =>特定元素

" scrolble -div" =>可滚动区域div

方法1:

document.querySelector('.automatic-scroll').scrollIntoView({
     behavior: 'smooth'
});

方法2:

location.href = "#automatic-scroll";

方法3:

$('#scrollable-div').animate({
   scrollTop: $('#automatic-scroll').offset().top - $('#scrollable-div').offset().top + 
   $('#scrollable-div').scrollTop()
})

重要注意:如果可滚动区域高度为“auto”,方法1和方法2将非常有用。方法3是有用的,如果我们使用滚动区域的高度,如“calc(100vh - 200px)”。

由于行为“平滑”不工作在Safari, Safari ios,浏览器。我通常使用requestAnimationFrame写一个简单的函数

(function(){
    var start;
    var startPos = 0;

    //Navigation scroll page to element
    function scrollTo(timestamp, targetTop){
      if(!start) start = timestamp
      var runtime = timestamp - start
      var progress = Math.min(runtime / 700, 1)

      window.scroll(0, startPos + (targetTop * progress) )

      if(progress >= 1){
        return;
      }else {
        requestAnimationFrame(function(timestamp){
            scrollTo(timestamp, targetTop)
        })
      }
   };

  navElement.addEventListener('click', function(e){

    var target = e.target  //or this 
    var targetTop = _(target).getBoundingClientRect().top
    startPos = window.scrollY

    requestAnimationFrame(function(timestamp){
        scrollTo(timestamp, targetTop)
    })
  }

})();