Dar*_*ren 7 javascript addeventlistener reactjs
我试图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});
}
}
Run Code Online (Sandbox Code Playgroud)
setState滚动时会这样500px.
如何500px在用户id="container"作为窗口顶部时替换要设置的条件?当用户到达div的底部时,也将isStuck状态替换为isStuckBottom.
完整的代码是
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});
}
}
Run Code Online (Sandbox Code Playgroud)
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")
}
});Run Code Online (Sandbox Code Playgroud)
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;
}Run Code Online (Sandbox Code Playgroud)
<div class="example">
</div>
<div id=container>
<div id=information></div></div>
<div class="bottom">
</div>Run Code Online (Sandbox Code Playgroud)