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

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

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

当前回答

在四处寻找之后,这是最后对我有用的方法:

找到/定位div在你的dom有滚动条。 对我来说,它看起来是这样的: "div class="table_body table_body_div" scroll_top="0" scroll_left="0" style="width: 1263px;身高:499 px;“ 我用这个xpath: //div[@class='table_body table_body_div'] 使用JavaScript像这样执行滚动: (JavascriptExecutor)司机).executeScript(“参数[0]。scrollLeft =参数[1];",元素,2000);

2000是我想向右滚动的像素数。 如果你想向下滚动div,使用scrollTop而不是scrollLeft。

注意:我尝试使用scrollIntoView,但它不能正常工作,因为我的网页有多个div。如果你只有一个集中注意力的主窗口,这是可行的。 如果你不想使用jQuery,这是我遇到的最好的解决方案。

其他回答

试试这个:

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

如@:

http://jsfiddle.net/Vgrey/

Chrome和Firefox

我一直在研究这个问题,我发现了这个问题,从某种程度上来说,这是最自然的方法。当然,这是我现在最喜欢的画卷。:)

const y = element.getBoundingClientRect().top + window.scrollY;
window.scroll({
  top: y,
  behavior: 'smooth'
});

IE、Edge和Safari的支持者

注意那个窗口。滚动({…options})在IE、Edge和Safari上不支持。在这种情况下,使用它可能是最好的 element.scrollIntoView()。(在IE 6上支持)。你很可能(读:未经测试)传入选项而没有任何副作用。

当然,这些可以被包装在一个函数中,根据所使用的浏览器来执行。

如果您只是想滚动到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> 

示例输出

焦点只能放在互动元素上…Div只表示页面的一个逻辑部分。

也许你可以在div周围设置边框,或者改变它的颜色来模拟焦点。是的,可见性不是焦点。

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

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)