搜索

首页  >  问答  >  正文

仅当在视口中时Javascript滚动IntoView

我制作了一个模型(请注意,它使用间隔,因为它在视频播放时滚动到新文本行)。我正在使用带有块的scrollIntoView:'nearest'。

问题是,由于整个页面都有滚动,它仍然滚动页面。我只是希望它滚动到lines div 中的活动文本行(它不必在视图中)。因为如果我正在查看“video”div,它将继续向下滚动(这是不需要的行为)。

var text = document.querySelector('.text')


setInterval(function() {
  text.scrollIntoView({
    behavior: 'smooth',
    block: 'nearest'
  });

}, 3000)
.a {
  height: 200px;
}

.elem {
  position: relative;
}

.video {
  width: 200px;
  height: 400px;
  background: #ccc;
  margin-bottom: 100px;
}

.lines {
  overflow-y: auto;
  height:120px;
}
<div class="a"></div>


<div class="elem">
  <div class="video"></div>


  <div class="lines">
    <div>lorem ipsum dolir sit amet</div>
    <div>Vestibulum nulla justo</div>
    <div>Fusce egestas, est ut fringilla facilisis</div>
    <div>Maecenas eu erat condimentum </div>
    <div>Quisque risus</div>
    <div>fames ac turpis egestas</div>
    <div>lorem ipsum dolir sit amet</div>
    <div>Vestibulum nulla justo</div>
    <div class="text">Fusce egestas, est ut fringilla facilisis</div>
    <div>Maecenas eu erat condimentum </div>
    <div>Quisque risus</div>
    <div>fames ac turpis egestas</div>

  </div>


</div>

<div class="a"></div>

P粉011684326P粉011684326447 天前489

全部回复(1)我来回复

  • P粉691958181

    P粉6919581812023-09-12 11:30:18

    正如您所发现的,scrollIntoView() 不适合您在此处尝试执行的操作 - 它会积极滚动多个视图窗格以尝试将您的元素放入视图中。< /p>

    更合适的是父元素上的 element.scrollTo(..) (在本例中为 .lines)。您需要进行一些高度算术以使元素在视口中居中,但这相对简单:

    var text = document.querySelector('.text')
    
    setInterval(function() {
      const parent       = text.parentElement;
      const parentHeight = parent.clientHeight;
      
      const textTop      = text.offsetTop - parent.offsetTop;
      const textMiddle   = textTop + text.offsetHeight / 2;
    
      parent.scrollTo({ top: textMiddle - parentHeight / 2, behavior: "smooth" });
    }, 3000)
    .a {
      height: 200px;
    }
    
    .elem {
      position: relative;
    }
    
    .video {
      width: 200px;
      height: 400px;
      background: #ccc;
      margin-bottom: 100px;
    }
    
    .lines {
      overflow-y: auto;
      height:120px;
    }
    
    .text {
      background: yellow;
    }
    <div class="a"></div>
    
    
    <div class="elem">
      <div class="video"></div>
    
    
      <div class="lines">
        <div>lorem ipsum dolir sit amet</div>
        <div>Vestibulum nulla justo</div>
        <div>Fusce egestas, est ut fringilla facilisis</div>
        <div>Maecenas eu erat condimentum </div>
        <div>Quisque risus</div>
        <div>fames ac turpis egestas</div>
        <div>lorem ipsum dolir sit amet</div>
        <div>Vestibulum nulla justo</div>
        <div class="text">Fusce egestas, est ut fringilla facilisis</div>
        <div>Maecenas eu erat condimentum </div>
        <div>Quisque risus</div>
        <div>fames ac turpis egestas</div>
    
      </div>
    
    
    </div>
    
    <div class="a"></div>

    回复
    0
  • 取消回复