我在一個頁面上有幾十個視頻。
當視頻被播放時,我改變了幾個屬性(背景為深色、增加視頻的大小、對齊到視頻中心、滾動到視頻頂部以便它是唯一顯示的元素,等等)。
我的腳本看起來像下面這樣:
document.querySelectorAll('div div video') 。 forEach(function(e) {
e.addEventListener('playing',function(event) {
e.style.width = ''/span>;
e.style.height = '95vh'。
e.closest('div').style.textAlign ='center';
e.closest('div').style.width='100%'。
e.previousElementSibling.style.color = '#ccc'/span>;
var pos = e.getBoundingClientRect();
window.scrollTo(0,pos.top - 40) 。
b = document.querySelector(body')。
b.style.backgroundColor = '#101010'。
});
});
問題是
var pos = e.getBoundingClientRect()。
window.scrollTo(0,pos.top -40) 。
上述代碼似乎只在滾動在頁面頂部的情況下起作用。如果人們在點擊播放之前已經向下滾動了頁面,那么滾動的位置最終會出現在錯誤的地方。
我在https://jsfiddle.net/017mxvbs/上創建了一個示例,以了解我的意思,在沒有滾動的情況下點擊視頻的播放。重繪 頁面,向下滾動并點擊最后一個視頻的播放。
那么,我做錯了什么呢?
uj5u.com熱心網友回復:
用offsetTop代替。
document.querySelectorAll('div div video') 。 forEach(function(e) {
e.addEventListener('playing',function(event) {
e.style.width = ''/span>;
e.style.height = '95vh'。
e.closest('div').style.textAlign ='center';
e.closest('div').style.width='100%'。
e.previousElementSibling.style.color = '#ccc'/span>;
window.scrollTo(0,e.offsetTop) 。
b = document.querySelector(body')。
b.style.backgroundColor = '#101010'。
});
});
更多關于getBoundingClientRect和offsetTop之間的區別的資訊在這里。getBoundingClientRect().top和 offsetTop之間的區別?
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/331532.html
標籤:
上一篇:如何設定javascript/node.js/npm?
下一篇:帶有while回圈的銷售稅計算器
