我试图将页面移动到<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';
当前回答
我们可以通过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)”。
其他回答
我经常使用滚动容器到其内容的方法。
/**
@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');
}
};
我认为如果你添加一个标签到你的div,它将能够获得焦点:
<div class="divFirst" tabindex="-1">
</div>
我不认为它是有效的,虽然,tabindex只能应用于一个,区域,按钮,输入,对象,选择和文本区域。但不妨试一试。
scrollIntoView工作良好:
document.getElementById("divFirst").scrollIntoView();
MDN文档中的完整引用: https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView
如果您只是想滚动到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>
示例输出
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上支持)。你很可能(读:未经测试)传入选项而没有任何副作用。
当然,这些可以被包装在一个函数中,根据所使用的浏览器来执行。