我正在構(gòu)建一個評論系統(tǒng),我希望用戶能夠從其他任何地方直接重定向到評論(就像堆棧溢出評論通知)。這是我到目前為止所得到的。(下面的demo顯示不太好,請參考codepen)const comment_box = document.getElementById('comment-box');const fourth = document.getElementById('btn4');const seventh = document.getElementById('btn7');const tenth = document.getElementById('btn10');function comment_jump(id){ var el = document.getElementById(id); // getBoundingClientRect: https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect // top (of this comment refer to parent) = top (of this comment refer to page) - top (of container refer to page) var tp = el.getBoundingClientRect().top - comment_box.offsetTop; comment_box.scrollTo(0, tp);}fourth.addEventListener('click', ()=>{ comment_jump('comment4');});seventh.addEventListener('click', ()=>{ comment_jump('comment7');});tenth.addEventListener('click', ()=>{ comment_jump('comment10');});body{ background: lightgrey;}#comment-box{ width: 500px; height: 300px; background: grey; overflow: auto;}.comment{ width: 100%; height: 33.3%; border: 1px solid; font-size: 2em; text-align: center; display: flex; justify-content: center; align-items: center; }button{ font-size: 1.5em; margin: 2em;}button:hover{ opacity: .5; cursor: pointer;}<div id="comment-box"> <div class="comment"></div> <div class="comment"></div> <div class="comment"></div> <div id="comment4" class="comment">4th</div> <div class="comment"></div> <div class="comment"></div> <div id="comment7" class="comment">7th</div> <div class="comment"></div> <div class="comment"></div> <div id="comment10" class="comment">10th</div> <div class="comment"></div> <div class="comment"></div></div><button type="button" id="btn4">4th</button><button type="button" id="btn7">7th</button><button type="button" id="btn10">10th</button>預(yù)期的輸出是,當(dāng)我點(diǎn)擊4th、7th、時10th,它會跳轉(zhuǎn)到相應(yīng)的區(qū)域。如果有人建議我哪一部分出錯了,我會很高興。
錨定溢出自動(可滾動)內(nèi)容
收到一只叮咚
2023-09-28 16:40:28