下面展示关键代码
const navigationBarData = [
{ key: "1", name: "首页" },
{ key: "2", name: "知识库" },
{ key: "3", name: "知识问答" },
{ key: "4", name: "专家库" },
{ key: "5", name: "排行榜" },
]; //定义导航栏
onScroll={() => { //滚动监听
navigationBarData.map((item) => { //遍历每个导航栏对应的内容
const mark = "#layout" + item.key;
const scrollTop =
document.getElementsByClassName("knowledgePortal")[0].scrollTop;
const dom = $(mark);
const offsetTop = dom.offset().top;
const outerHeight = dom.outerHeight();
if (
offsetTop - scrollTop <= 0 &&
offsetTop + outerHeight - scrollTop > 0
) { //判断当前导航栏是否处于页面视口中,是的话就将此导航加上选中样式,此判断也可以使用下方原生js方法实现
this.setState({
navigationValue: item.key,
});
}
});
}}
判断视口内也可以使用原生js方法来实现,如下
function isInViewport(element) { //判断方法
const rect = element.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
const myElement = document.querySelector('#data-board-sales-hopper'); //获取需要判断的dom
if (isInViewport(myElement)) {
alert('该元素在视口内')
} else {
alert('该元素不在视口内')
}