我做了一個模型(注意,這是使用間隔,因為它是滾動到新的視頻播放文本行)。我將scrollIntoView與block一起使用:“nearest”。
問題是,由于整個頁面已經滾動,它仍然滾動頁面。我只是想讓它滾動到行div中的活動文本行(它不必在視圖中)。因為如果我往里看& quot視頻& quotdiv,它將繼續向下滾動(這是不希望出現行為)。
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>
正如您已經發現的,scrollIntoView()并不適合您在這里嘗試做的事情——它會積極地滾動多個視圖窗格,以嘗試將您的元素放入視圖中。
更合適的是element.scrollTo(..)在父元素(。在這種情況下是線)。您需要做一點高度運算來使元素在視口中居中,但這相對簡單:
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>
下一篇vue 獲取路由對象