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

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

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

当前回答

试试这个函数

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

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

其他回答

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

试试这个函数

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

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

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

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

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

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

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

node.focus ()

node . removeAttribute(“tabindex”)

你可以使用一个锚来“聚焦”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";