亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使頁面滾動以將 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 關注
  • 190 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號