gpt4 book ai didi

javascript - 当 div ID 位于窗口顶部时有条件的 addEventListener

转载 作者:数据小太阳 更新时间:2023-10-29 04:43:21 26 4
gpt4 key购买 nike

我正在尝试使用 addEventListener当用户 scroll进入视野<div id="container"> .我是通过滚动高度来完成的,但我尝试 addEventListener什么时候<div>位于窗口顶部。

handleHeaderStuck = () => {
if (this.innerContainer.scrollTop <= 500 && this.state.isStuck === true) {
this.setState({isStuck: false});
}
else if (this.innerContainer.scrollTop >= 500 && this.state.isStuck !== true) {
this.setState({isStuck: true});
}
}

这将 setState滚动时 500px .

如何替换 500px 的条件当用户使用 id="container" 时设置作为窗口的顶部?同时替换 isStuck状态为 isStuckBottom当用户到达 div 的底部时。

完整代码为

constructor(props) {
super(props)
this.state = {
isStuck: false,
}
this.handleHeaderStuck = this.handleHeaderStuck.bind(this)
}

innerContainer = null

componentDidMount () {
this.innerContainer.addEventListener("scroll", this.handleHeaderStuck);
}

componentWillUnmount () {
this.innerContainer.removeEventListener("scroll", this.handleHeaderStuck);
}

handleHeaderStuck = () => {
if (this.innerContainer.scrollTop <= 500 && this.state.isStuck === true) {
this.setState({isStuck: false});
}
else if (this.innerContainer.scrollTop >= 500 && this.state.isStuck !== true) {
this.setState({isStuck: true});
}
}

最佳答案

  var atTop = false;
var atBotton = false;
document.addEventListener("scroll", e => {

var elemInfo = document.getElementById("container").getClientRects()[0];
if (parseInt(elemInfo.bottom) >= window.innerHeight)
{
if (!atBottom){
console.log("I touche the bottom")
document.getElementById("information").innerHTML = "mouse reached the bottom";
atBottom = true;
}
atTop = false;
} else if (parseInt(elemInfo.top) <= 0) {
if (!atTop) {
console.log("Mouse at top")
document.getElementById("information").innerHTML = "I touched the top";
atTop = true;
}
atBottom = false;
} else {
console.log("I touched the nothing")
}
});
body {
margin: 0px;
padding: 0px;
border: 0px;
}

.first, .bottom {
width: 100%;
height: 200px;
background-color: Green;
}

#container {
width: 100%;
background-color: Yellow;
margin: 0px;
padding: 0px;
border: 1 px solid black;
height: 200px;
}

#infomation {
font-size: 50px;
}
    <div class="example">

</div>
<div id=container>
<div id=information></div></div>
<div class="bottom">

</div>

关于javascript - 当 div ID 位于窗口顶部时有条件的 addEventListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50010159/

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