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

我正在构建一个页面,其中有一些具有不同高度的 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>


浮云间
浏览 116回答 2
2回答

人到中年有点甜

如果我正确理解你,这将帮助你。let divs = document.querySelectorAll(".element");divs.forEach(div => {&nbsp; &nbsp; div.addEventListener("click", event =>{&nbsp; &nbsp; &nbsp; &nbsp; let divTop = div.offsetTop;&nbsp; &nbsp; &nbsp; &nbsp; window.scrollTo(0, divTop);&nbsp; &nbsp; &nbsp; &nbsp; console.log(divTop + " --- " + window.scrollY);&nbsp; &nbsp; });});.container {&nbsp; &nbsp; width: 100vw;&nbsp; &nbsp; height: auto;}.element {&nbsp; &nbsp; padding: 50px;}#element-1 {&nbsp; &nbsp; background-color: beige;&nbsp; &nbsp; height: 500px;}#element-2 {&nbsp; &nbsp; background-color: darkSeaGreen;&nbsp; &nbsp; height: 200px;}#element-3 {&nbsp; &nbsp; background-color: coral;&nbsp; &nbsp; color:&nbsp; white;&nbsp; &nbsp; height: 800px;}#element-4 {&nbsp; &nbsp; background-color: MidnightBlue;&nbsp; &nbsp; color: white;&nbsp; &nbsp; height: 300px;}<div class="container">&nbsp; <div class="element" id="element-1">&nbsp; &nbsp; <h1>Some text</h1>&nbsp; </div>&nbsp; <div class="element" id="element-2">&nbsp; &nbsp; <h1>Some text</h1>&nbsp; </div>&nbsp; <div class="element" id="element-3">&nbsp; &nbsp; <h1>Some text</h1>&nbsp; </div>&nbsp; <div class="element" id="element-4">&nbsp; &nbsp; <h1>Some text</h1>&nbsp; </div></div>

UYOU

您需要实现一个执行此操作的功能window.scrollTo(x,&nbsp;0);其中 x 是元素的位置。你可以通过使用let&nbsp;x&nbsp;=&nbsp;element.getBoundingClientRect().top;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript