前端小功能:新手引導高亮


前端小功能:新手引導高亮

其實就是一個遮罩層加一個彈窗,只不過比一般彈窗稍微復雜一點的是,遮罩層之上除了彈窗之外,還有需要高亮引導的元素區域,並且彈窗的位置也並不是固定的,而是跟隨高亮引導區域進行定位。

border實現:

這種實現方法只用到了一個額外元素,使用 toprightbottomleft 四個元素分別使用一個元素的四條邊(border)來代替,相比於正常元素的border來說,這個元素的border-width會比較大,以至於可以填充滿除了 新功能區域 之外頁面剩余的區域,再將 border-color設置為正常遮罩層的背景色,border就偽裝好了。

直接使用代碼:

/* eslint-disable valid-jsdoc */
export function HighlightBoot() {
  this.clientHeight =
    document.documentElement.clientHeight || document.body.clientHeight;
  this.clientWidth =
    document.documentElement.clientWidth || document.body.clientHeight;
  /**
   *
   * @param id 高亮DOM
   */
  this.openBoot = ({ id = '' }) => {
    const domId = document.getElementById(id);
    if (!domId) {
      throw new Error('id 選擇標識無效');
    }
    const element = document.documentElement;
    const { top: initTop, height: initHeight } = domId.getBoundingClientRect();
    // 是否在可視區域
    const customHeight = 70; // 出現底部導航欄時需要減去高度
    if (initHeight + initTop > this.clientHeight - customHeight) {
      const scrollHeight =
        initHeight + initTop - (this.clientHeight - customHeight);
      element.scrollTop = scrollHeight;
    }
    // 關閉頁面滾動
    element.style.overflow = 'hidden';
    // 重新計算位置
    const domMockId = document.getElementById(id);
    const { top, left, width, height } = domMockId.getBoundingClientRect();

    // 創建高亮mock蒙版
    const domMock = document.createElement('div');
    domMock.setAttribute(
      'style',
      `position: fixed;
      top:0;
      left:0;
      border:1px solid rgba(0,0,0,0.5);
      z-index: 99999;
      border-top-width: ${top}px;
      border-right-width: ${this.clientWidth - left - width}px;
      border-bottom-width: ${this.clientHeight - height - top}px;
      border-left-width: ${left}px;
      width: ${width}px;
      height: ${height}px; `
    );
    element.appendChild(domMock);

    const closeMock = document.createElement('div');
    closeMock.innerText = '×';
    closeMock.setAttribute(
      'style',
      `position: absolute;
      top: -30px;
      cursor: pointer;
      left: ${width}px;
      font-size: 14px;
      color: #fff;
      z-index: 2;
      text-align: center;
      line-height: 30px;
      border-radius: 50%;
      border: 1px solid #fff;
      width: 30px;
      height: 30px; `
    );
    domMock.appendChild(closeMock);

    closeMock.addEventListener('click', () => {
      element.removeChild(domMock);
      element.style.overflow = 'auto';
    });
  };
}

export default HighlightBoot;

直接上對象了,擴展自定義的配置就靠自己去處理了。

const boot = new HighlightBoot();
boot.openBoot({ id: 'notice-tip' });

注意:當頁面異步加載,頁面結構會改變元素位置的時候,需要在頁面更新完成后再調用。

 

 

沒有終點,沒有彼岸,堅持就好,願歲月如初


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM