我製作了一個模型(請注意,它使用間隔,因為它在視訊播放時滾動到新文字行)。我正在使用帶有區塊的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粉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>