場景
React頁面中,不確定有多少個(gè)需要定位的塊,根據(jù)元素塊的個(gè)數(shù),生成對應(yīng)數(shù)量的錨點(diǎn),點(diǎn)擊錨點(diǎn)后頁面滾動(dòng)到指定的塊。 頁面滾動(dòng)到指定的塊,對應(yīng)的錨點(diǎn)高亮。
錨點(diǎn)
超鏈接的一種形式,快速定位到想要看的位置,常用在文章目錄等位置。
實(shí)現(xiàn)
- dom元素方面
// dom
<div
id="know-detail-body"
onScrollCapture={() => this.onScrollEvent()}
style={{ height: '200px', overflowY: 'scroll' }}
ref={(c) => {
this.scrollRef = c;
}}
>
<div className="content">
<div id="content-div">
{contentOptions}
</div>
</div>
<div className="anchor-link-body" id="know-link-anchor">
<div className="link-content-link">
<span />
</div>
<div id="link-contentKey">
{LinkOptions}
</div>
</div>
</div>
- 構(gòu)造對象,動(dòng)態(tài)生成元素,對象從接口獲取,數(shù)目不定,這是個(gè)demo
/*
ObjectList:[
{id: 1, name: '橘子'},
{id: 2, name: '蘋果'},
{id: 3, name: '香蕉'},
{id: 4, name: '菠蘿'},
]
*/
// 根據(jù)數(shù)組生成對應(yīng)的模塊, 在render函數(shù)內(nèi)面
const contentOptions = [];
const LinkOptions = [];
ObjectList.forEach((item) => {
LinkOptions.push(<div id={`link-${item.id}`} className="link-content" onClick={this.scrollToAnchor.bind(this, item.id)}>{item.name}</div>)
contentOptions .push(
<div className="content-child">
<span id={`${item.id}`}>{item.name}</span>
<div style={{ width: '100%', heigth: '500px' }}>
我是內(nèi)容,我是內(nèi)容
</div>
</div>
)
});
- 點(diǎn)擊錨點(diǎn),對于的塊滑動(dòng)到瀏覽器窗口的頂部方法
// 這是滾動(dòng)方法
scrollToAnchor = (anchorName) => {
if (anchorName || anchorName === 0) {
// 找到錨點(diǎn)
const anchorElement = document.getElementById(anchorName);
// 如果對應(yīng)id的錨點(diǎn)存在,就跳轉(zhuǎn)到錨點(diǎn)
if (anchorElement) {
anchorElement.scrollIntoView({
block: 'start',
behavior: 'smooth',
});
}
}
};
- 生命周期函數(shù)中獲取所有元素的id集合
componentDidMount() {
this.getBoxIds();
}
/**
* 1. 在React生命周期函數(shù)中執(zhí)行函數(shù)
* 2. 獲取每個(gè)塊的正文內(nèi)容初始距離瀏覽器邊框的距離 offsetTop
*/
getBoxIds = () => {
// 正文板塊綁定的id數(shù)組
const linkIds = [];
ObjectList.forEach((item, index) => {
const top = document.getElementById(`${item.id}`);
if (top) {
linkIds.push({ key: item.id, offsetTop: top.getBoundingClientRect().top});
}
})
this.setState({ linkIds });
};
- 監(jiān)聽頁面滾動(dòng),操作dom,使導(dǎo)航的錨點(diǎn)高亮
/**
* activeLink -- 高亮的類名,屬性在css中自行設(shè)置
* linkIds -- 錨點(diǎn)對應(yīng)div id集合的數(shù)組
* this.scrollRef.scrollTop 滾動(dòng)條滾動(dòng)的距離
*/
onScrollEvent() {
const { linkIds } = this.state;
linkIds.forEach((item, index) => {
if (this.scrollRef.scrollTop > item.offsetTop) {
document.getElementById(`link-${item.key}`).classList.add('activeLink');
linkIds.forEach((k, v) => {
if (item.key !== k.key) {
document.getElementById(`link-${k.key}`).classList.remove('activeLink');
}
});
}
});
}
github地址
demo項(xiàng)目:
- npm install
- npm start
https://github.com/fyxwanan/author-demo