我正在尝试在每个div触摸浏览器窗口顶部时触发一个函数。但它随机出现,请阅读以下内容以查看问题。
在加载组件时,我将放置事件并滚动并测量div的高度,我将在以后使用它。
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
let heightCounter = document.getElementsByClassName("js_event_height");
this.setState({
heightOfItem: heightCounter[0].offsetHeight
});
}
我正在使用该对象和状态
state = {
idEventItem: 0,
currentEvent: 0,
heightOfItem: 0,
eventList: [
{
id: 0,
name: "xy",
location: "loc1",
top: '10%',
left: '10%'
},
{
id: 1,
name: "xxx",
location: "loc2",
top: '20%',
left: '20%'
},
{
id: 2,
name: "xyx",
location: "loc3",
top: '30%',
left: '30%'
},
{
id: 3,
name: "xyxyx",
location: "loc4",
top: '40%',
left: '40%'
},
{
id: 4,
name: "xyz",
location: "loc4",
top: '38.486%',
left: '29.18%'
}
]
};
这是我要执行的功能,当每个div的顶部触摸浏览器的顶部时,我会更改点在地图上的位置。我从0开始,计数像素滚动,当我到达div的高度时,我更改了id以获取正确的坐标,如果返回,我将向后做同样的事情。但是问题在于它不能正确地更改id,它会弄乱,我看不到原因。
handleScroll = () => {
let scrollTop = window.scrollY;
if (scrollTop > (this.state.heightOfItem * this.state.idEventItem)) {
this.chengePoisitionOfPointerOnMap(this.state.idEventItem);
this.setState({
idEventItem: this.state.idEventItem + 1
});
console.log('proslo je kroz jedan' + this.state.idEventItem)
} else if (scrollTop < (this.state.heightOfItem * (this.state.idEventItem - 1))) {
this.chengePoisitionOfPointerOnMap(this.state.idEventItem);
this.setState({
idEventItem: this.state.idEventItem - 1
});
}
}
这就是我尝试更改点的位置的方法
chengePoisitionOfPointerOnMap = (locationElement) =>{
console.log(locationElement + ' location element')
let left = this.state.eventList[locationElement].left;
let top = this.state.eventList[locationElement].top;
document.getElementById("location_pointer").style.left = left;
document.getElementById("location_pointer").style.top = top;
}