我正在构建一个页面,其中有一些不同高度的div和一个文本,当我点击div的文本时,我想让页面移动,这样这个div就会出现在屏幕的顶部。
我到处搜索,但我发现经常与固定属性有关,问题是我不想更改div的position属性,我只想让页面自动滚动,这样div就会在顶部。
你对我可以从哪里开始有什么建议吗?
谢谢
.container {
width: 100vw;
height: auto;
}
.element {
padding: 50px;
}
#element-1 {
background-color: beige;
height: 500px;
}
#element-2 {
background-color: darkSeaGreen;
height: 200px;
}
#element-3 {
background-color: coral;
color: white;
height: 800px;
}
#element-4 {
background-color: MidnightBlue;
color: white;
height: 300px;
}<div class="container">
<div class="element" id="element-1">
<h1>Some text</h1>
</div>
<div class="element" id="element-2">
<h1>Some text</h1>
</div>
<div class="element" id="element-3">
<h1>Some text</h1>
</div>
<div class="element" id="element-4">
<h1>Some text</h1>
</div>
</div>
发布于 2020-09-21 05:15:11
如果我没弄错的话,这会对你有帮助的。
let divs = document.querySelectorAll(".element");
divs.forEach(div => {
div.addEventListener("click", event =>{
let divTop = div.offsetTop;
window.scrollTo(0, divTop);
console.log(divTop + " --- " + window.scrollY);
});
});.container {
width: 100vw;
height: auto;
}
.element {
padding: 50px;
}
#element-1 {
background-color: beige;
height: 500px;
}
#element-2 {
background-color: darkSeaGreen;
height: 200px;
}
#element-3 {
background-color: coral;
color: white;
height: 800px;
}
#element-4 {
background-color: MidnightBlue;
color: white;
height: 300px;
}<div class="container">
<div class="element" id="element-1">
<h1>Some text</h1>
</div>
<div class="element" id="element-2">
<h1>Some text</h1>
</div>
<div class="element" id="element-3">
<h1>Some text</h1>
</div>
<div class="element" id="element-4">
<h1>Some text</h1>
</div>
</div>
发布于 2020-09-21 05:03:13
您需要实现一个执行此操作的函数
window.scrollTo(x, 0); 其中x是元素的位置。你可以通过使用下面的命令来实现
let x = element.getBoundingClientRect().top;https://stackoverflow.com/questions/63983604
复制相似问题