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

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

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

当前回答

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

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

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

其他回答

试试这个函数

function navigate(divId) {
$j('html, body').animate({ scrollTop: $j("#"+divId).offset().top }, 1500);
}

传递div id作为参数,它将工作,我已经在使用它

试试这个:

var divFirst = document.getElementById("divFirst");
divFirst.style.visibility = 'visible'; 
divFirst.style.display = 'block';  
divFirst.tabIndex = "-1";  
divFirst.focus();

如@:

http://jsfiddle.net/Vgrey/

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

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周围设置边框,或者改变它的颜色来模拟焦点。是的,可见性不是焦点。

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

/**
@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');
    }
};