gpt4 book ai didi

javascript - 如何获取向上滚动的 div 的更新顶部位置?

转载 作者:行者123 更新时间:2023-11-30 15:31:06 25 4
gpt4 key购买 nike

http://codepen.io/leongaban/pen/YNBgqE

滚动 #tickers-col 后,如何获得正确更新的 div 顶部位置?

从日志来看,无论列向上移动多远,它仍然显示 div 的原始 y 位置:

enter image description herecolPos 对象 {x: 8, y: 8}

const tickersCol = document.getElementById("tickers-col");


// https://stackoverflow.com/questions/288699/get-the-position-of-a-div-span-tag
function getPos(el) {
for (var lx=0, ly=0;
el != null;
lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
return {x: lx,y: ly};
}

function mouseHover() {
const colPos = getPos(tickersCol);
console.log('colPos', colPos)
}
.container {
position: fixed;
font-family: Arial;
}

#tickers-col {
overflow-y: auto;
height: 400px;
}

li {
margin-bottom: 10px;
list-style: none;
padding: 5px 10px;
width: 120px;
color: white;
background: salmon;
border-radius: 4px;
cursor: pointer;
}
<div class="container">
<div id="tickers-col">
<ul>
<li onmouseenter="mouseHover()">aaa</li>
<li onmouseenter="mouseHover()">bbb</li>
<li onmouseenter="mouseHover()">ccc</li>
<li onmouseenter="mouseHover()">ddd</li>
<li onmouseenter="mouseHover()">eee</li>
<li onmouseenter="mouseHover()">fff</li>
<li onmouseenter="mouseHover()">ggg</li>
<li onmouseenter="mouseHover()">hhh</li>
<li onmouseenter="mouseHover()">iii</li>
<li onmouseenter="mouseHover()">jjj</li>
<li onmouseenter="mouseHover()">kkk</li>
<li onmouseenter="mouseHover()">lll</li>
<li onmouseenter="mouseHover()">mmm</li>
<li onmouseenter="mouseHover()">nnn</li>
<li onmouseenter="mouseHover()">ooo</li>
<li onmouseenter="mouseHover()">ppp</li>
<li onmouseenter="mouseHover()">qqq</li>
<li onmouseenter="mouseHover()">rrr</li>
<li onmouseenter="mouseHover()">sss</li>
<li onmouseenter="mouseHover()">ttt</li>
<li onmouseenter="mouseHover()">uuu</li>
<li onmouseenter="mouseHover()">vvv</li>
<li onmouseenter="mouseHover()">www</li>
<li onmouseenter="mouseHover()">yyy</li>
<li onmouseenter="mouseHover()">xxx</li>
<li onmouseenter="mouseHover()">zzz</li>
</ul>
</div>
</div>

从这里找到getPos 函数:Get the position of a div/span tag

最佳答案

所以,我真的不明白你到底想做什么,但根据定义,元素的 offsetTop 属性将返回相对于 offsetParent 元素顶部的顶部位置(以像素为单位)。

因此,无论您滚动多长时间,如果您正在检查的元素与其父元素之间的顶部距离没有改变,您的顶部值就不会改变。

也许您正在寻找的属性是scrollTop

const getPos = (el) => {
for (var lx=0, ly=0;
el != null;
lx += el.offsetLeft, ly += el.scrollTop, el = el.offsetParent);
return { x:lx, y:ly };
}

关于javascript - 如何获取向上滚动的 div 的更新顶部位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42232205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com