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

锚定溢出自动(可滚动)内容

锚定溢出自动(可滚动)内容

收到一只叮咚 2023-09-28 16:40:28
我正在构建一个评论系统,我希望用户能够从其他任何地方直接重定向到评论(就像堆栈溢出评论通知)。这是我到目前为止所得到的。(下面的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>预期的输出是,当我点击4th、7th、时10th,它会跳转到相应的区域。如果有人建议我哪一部分出错了,我会很高兴。
查看完整描述

1 回答

?
潇潇雨雨

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

我可以建议尝试scrollIntoView作为可能的解决方案吗?


function comment_jump(id){

    var el = document.getElementById(id);

    el.scrollIntoView();

}


来自 Mozilla 的文档:


scrollIntoView() 方法滚动元素的父容器,以便用户可以看到调用scrollIntoView() 的元素


因此,它会将注释容器滚动到所需的元素。


查看完整回答
反对 回复 2023-09-28
  • 1 回答
  • 0 关注
  • 47 浏览
慕课专栏
更多

添加回答

举报

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