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

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

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

当前回答

我们可以通过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)”。

其他回答

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

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

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

你可以使用一个锚来“聚焦”div。例如:

<div id="myDiv"></div>

然后使用下面的javascript:

// the next line is required to work around a bug in WebKit (Chrome / Safari)
location.href = "#";
location.href = "#myDiv";

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

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

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

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

/**
@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 navigate(divId) {
$j('html, body').animate({ scrollTop: $j("#"+divId).offset().top }, 1500);
}

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