場景
React頁面中,不確定有多少個需要定位的塊,根據元素塊的個數,生成對應數量的錨點,點擊錨點后頁面滾動到指定的塊。 頁面滾動到指定的塊,對應的錨點高亮。
錨點
超鏈接的一種形式,快速定位到想要看的位置,常用在文章目錄等位置。
實現
- 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>
- 構造對象,動態生成元素,對象從接口獲取,數目不定,這是個demo
/*
ObjectList:[
{id: 1, name: '橘子'},
{id: 2, name: '蘋果'},
{id: 3, name: '香蕉'},
{id: 4, name: '菠蘿'},
]
*/
// 根據數組生成對應的模塊, 在render函數內面
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' }}>
我是內容,我是內容
</div>
</div>
)
});
- 點擊錨點,對于的塊滑動到瀏覽器窗口的頂部方法
// 這是滾動方法
scrollToAnchor = (anchorName) => {
if (anchorName || anchorName === 0) {
// 找到錨點
const anchorElement = document.getElementById(anchorName);
// 如果對應id的錨點存在,就跳轉到錨點
if (anchorElement) {
anchorElement.scrollIntoView({
block: 'start',
behavior: 'smooth',
});
}
}
};
- 生命周期函數中獲取所有元素的id集合
componentDidMount() {
this.getBoxIds();
}
/**
* 1. 在React生命周期函數中執行函數
* 2. 獲取每個塊的正文內容初始距離瀏覽器邊框的距離 offsetTop
*/
getBoxIds = () => {
// 正文板塊綁定的id數組
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 });
};
- 監聽頁面滾動,操作dom,使導航的錨點高亮
/**
* activeLink -- 高亮的類名,屬性在css中自行設置
* linkIds -- 錨點對應div id集合的數組
* this.scrollRef.scrollTop 滾動條滾動的距離
*/
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項目:
- npm install
- npm start
https://github.com/fyxwanan/author-demo