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

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

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

当前回答

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

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

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

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

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

其他回答

您可以将焦点设置为元素。它比scrollIntoView工作得更好

node。setAttribute(“tabindex”、“- 1”)

node.focus ()

node . removeAttribute(“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');
    }
};

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

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

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

如果您只是想滚动到div中列表的底部,您可以这样做。

<body>

<div class="container">
    <div class="box">1</div>
    <div class="box">2</div>
    <div class="box">3</div>
    <div class="box">4</div>
    <div class="box">5</div>
    <div class="box">6</div>
    <div class="box">7</div>
    <div class="box">8</div>
    <div class="box">9</div> 
</div>
<button>Scroll To</button>

    <script> 
        const btn = document.querySelector("button");
        const container = document.querySelector(".container"); 
        btn.addEventListener("click",()=>{
        const toplast = document.querySelector(".container").lastElementChild;
        toplast.scrollIntoView();
    })
    </script>
</body> 

示例输出

scrollIntoView工作良好:

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

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