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

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

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

当前回答

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

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

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

其他回答

你不能聚焦在一个div上。你只能聚焦在该div中的一个输入元素上。此外,你需要使用element.focus()而不是display()

我经常使用滚动容器到其内容的方法。

/**
@param {HTMLElement} container : element scrolled.
@param {HTMLElement} target : element where to scroll.
@param {number} [offset] : scroll back by offset
*/
var scrollAt=function(container,target,offset){
    if(container.contains(target)){
        var ofs=[0,0];
        var tmp=target;
        while (tmp!==container) {
            ofs[0]+=tmp.offsetWidth;
            ofs[1]+=tmp.offsetHeight;
            tmp=tmp.parentNode;
        }
        container.scrollTop = Math.max(0,ofs[1]-(typeof(offset)==='number'?offset:0));
    }else{
        throw('scrollAt Error: target not found in container');
    }
};

如果你想覆盖全局,你也可以这样做:

HTMLElement.prototype.scrollAt=function(target,offset){
    if(this.contains(target)){
        var ofs=[0,0];
        var tmp=target;
        while (tmp!==this) {
            ofs[0]+=tmp.offsetWidth;
            ofs[1]+=tmp.offsetHeight;
            tmp=tmp.parentNode;
        }
        container.scrollTop = Math.max(0,ofs[1]-(typeof(offset)==='number'?offset:0));
    }else{
        throw('scrollAt Error: target not found in container');
    }
};

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

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)

我认为如果你添加一个标签到你的div,它将能够获得焦点:

<div class="divFirst" tabindex="-1">
</div>

我不认为它是有效的,虽然,tabindex只能应用于一个,区域,按钮,输入,对象,选择和文本区域。但不妨试一试。

如果你想使用html,你可以使用这个:

a href="samplewebsite.com/subdivision.html#id

并将其作为指向特定元素id的HTML链接。它基本上是getElementById html版本。