我试图将页面移动到<div>元素。
我已经尝试了下一个代码无效:
document.getElementById("divFirst").style.visibility = 'visible';
document.getElementById("divFirst").style.display = 'block';
我试图将页面移动到<div>元素。
我已经尝试了下一个代码无效:
document.getElementById("divFirst").style.visibility = 'visible';
document.getElementById("divFirst").style.display = 'block';
当前回答
类似于@穴居人的解决方案
const element = document.getElementById('theelementsid');
if (element) {
window.scroll({
top: element.scrollTop,
behavior: 'smooth',
})
}
其他回答
你可以使用一个锚来“聚焦”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";
scrollIntoView工作良好:
document.getElementById("divFirst").scrollIntoView();
MDN文档中的完整引用: https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView
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在你的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,这是我遇到的最好的解决方案。