React + es6使用雙向錨點(diǎn),動(dòng)態(tài)生成,也適用單頁面路由項(xiàng)目

場景

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)目:

預(yù)覽地址

https://fyxwanan.github.io/author-demo/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 問答題47 /72 常見瀏覽器兼容性問題與解決方案? 參考答案 (1)瀏覽器兼容問題一:不同瀏覽器的標(biāo)簽?zāi)J(rèn)的外補(bǔ)...
    _Yfling閱讀 14,108評論 1 92
  • ??JavaScript 與 HTML 之間的交互是通過事件實(shí)現(xiàn)的。 ??事件,就是文檔或?yàn)g覽器窗口中發(fā)生的一些特...
    霜天曉閱讀 3,684評論 1 11
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML標(biāo)準(zhǔn)。 注意:講述HT...
    kismetajun閱讀 28,797評論 1 45
  • 第一章 1、使用瀏覽器去訪問的程序,叫網(wǎng)頁 2、web代碼存放在服務(wù)器 代碼分為兩種:① 運(yùn)行在瀏覽器端:前端代...
    fastwe閱讀 3,551評論 0 2
  • 我兄弟老董,就是上回餐桌上講拐賣女研究生那貨。 人到中年,倆孩子的爹。 最近危機(jī)了,中年危機(jī)。 大抵說到男人的中年...
    用心是吉閱讀 296評論 1 4

友情鏈接更多精彩內(nèi)容