[英]Changing div position to fixed with javascript attaches the div to document not viewport
我正在尋找一種方法來確定 div 的任何部分是否接觸視口的頂部,並使用 vanilla javascript 將該 div 中的項目修復到視口的頂部。
我已經能夠理清如何確定 div 是否正在觸摸視口的頂部並觸發對 div 樣式的更改。 但是由於某種原因,當我將 div 的position: absolute
更改為position: fixed
時,將 div 修復固定到文檔的頂部,而不是視口的頂部,因此不可見。
我的js
function touchTop() {
var div = $('itin');
var rect = div.getBoundingClientRect();
var y = rect.top;
var h = rect.bottom;
if ((y < 0) && (h > 0)) {
document.getElementById('seemore').style.position = 'fixed';
document.getElementById('seemore').style.top = '45%';
} else {
document.getElementById('seemore').style.position = 'absolute';
document.getElementById('seemore').style.top = '66px';
}
}
window.addEventListener('scroll', touchTop);
基本 div HTML
<div id="itin" class="container">
<div class="sp20"></div>
<div class="text rgt">
<h3>your daily adventures</h3>
<p>blah blah blah</p>
</div>
<div id="seemore" class="ghstbtn">See More</div>
</div>
和基本初始CSS
#seemore {
width: auto;
position: absolute;
top: 66px;
right: 20px;
}
進一步澄清:我需要解決的問題是,當 javascript 更改 style.position 以固定 #seemore div 的位置時,“top”值是從文檔頂部而不是從視口頂部測量的。 所以在視口中基本上不可見。
如果我理解正確,我認為您的問題出在此處:
if ((y < 0) && (h > 0))
當容器 div 到達文檔頂部時,position 到“seemore”設置為固定,但是當 div 底部到達文檔頂部時,“h === 0”和 position 再次設置到絕對。
嘗試這個。
const seeMore = document.getElementById('seemore');
const div = document.getElementById('itin');
window.addEventListener('scroll', checkBoundries);
function checkBoundries() {
var rect = div.getBoundingClientRect();
var y = rect.top;
var h = rect.bottom;
if (y < 0) {
seeMore.style.position = 'fixed';
seeMore.style.top = '45%';
} else {
seeMore.style.position = 'absolute';
seeMore.style.top = '66px';
}
}
原來與應用於...的父級的父級的父級的過濾器有關。
發現一些關於轉換問題和 position:fixed 的老問題可以追溯到大約 5 到 7 年前。 盡管許多人提到向瀏覽器制造商提交問題報告,但問題似乎從未得到解決和解決。 一條評論提到過濾器也可能導致問題。
將過濾器移動到一個單獨的 class 現在添加和刪除,而不是將過濾器直接應用於 div。 一切都按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.