为了账号安全,请及时绑定邮箱和手机立即绑定

使页面滚动以将 div 放在顶部

使页面滚动以将 div 放在顶部

浮云间 2023-03-18 16:46:45
我正在构建一个页面,其中有一些具有不同高度的 div 和其中的文本,我想在单击 div 的文本时移动页面,以便该 div 位于屏幕顶部.我四处搜索,但我发现的通常与固定属性有关,问题是我不想更改 div 的位置属性,我只想让页面自动滚动,这样 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>
查看完整描述

2 回答

?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

如果我正确理解你,这将帮助你。


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>


查看完整回答
反对 回复 2023-03-18
?
UYOU

TA贡献1878条经验 获得超4个赞

您需要实现一个执行此操作的功能

window.scrollTo(x, 0);

其中 x 是元素的位置。你可以通过使用

let x = element.getBoundingClientRect().top;


查看完整回答
反对 回复 2023-03-18
  • 2 回答
  • 0 关注
  • 114 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信