vue,底層方法scroll.js

scroll 方法彙集

// import { isServer } from './index'

const isServer = false;

// [debounce 和 throttle](https://www.cnblogs.com/wilber2013/p/5893426.html)

// const docE = document.documentElement
// const docBody = document.body

/**
 * 觸發高度
 * 文檔總高度 - (滾動條距離頂部高度 + 當前可視的頁面高度) < 觸發高度
 * scrollHeight - (scrollTop + visibleHeight|clientHeight) < offset
 *
 */
export default {
  /**
   * const pos = getPageScrollPos()
   * const reachBottom = pos.pageHeight - (pos.top + pos.height)
   *
   * @returns object
   */
  // getPageScrollPos(a = docE, b = docBody) {
  //   const top = Math.max(a.scrollTop, b.scrollTop)
  //   const left = Math.max(a.scrollLeft, b.scrollLeft)
  //   const width = Math.min(a.clientWidth, b.clientWidth)
  //   const height = Math.min(a.clientHeight, b.clientHeight)
  //   const pageWidth = Math.max(a.scrollWidth, b.scrollWidth)
  //   const pageHeight = Math.max(a.scrollHeight, b.scrollHeight)

  //   return {
  //     top,
  //     left,
  //     height,
  //     width,
  //     pageWidth,
  //     pageHeight,
  //   }
  // },
  /* 找到最近的觸發滾動事件的元素
   * @param {Element} element
   * @param {Element} rootElement
   * @return {Element | window}
   */
  getScrollEventTarget(element, rootParent = window) {
    let currentNode = element;
    // bugfix
    while (
      currentNode &&
      currentNode.tagName !== 'HTML' &&
      currentNode.tagName !== 'BODY' &&
      currentNode.nodeType === 1 &&
      currentNode !== rootParent
    ) {
      const { overflowY } = this.getComputedStyle(currentNode);
      if (overflowY === 'scroll' || overflowY === 'auto') {
        return currentNode;
      }
      currentNode = currentNode.parentNode;
    }
    return rootParent;
  },

  // 判斷元素是否被加入到頁面節點內
  isAttached(element) {
    let currentNode = element.parentNode;
    while (currentNode) {
      if (currentNode.tagName === 'HTML') {
        return true;
      }
      if (currentNode.nodeType === 11) {
        return false;
      }
      currentNode = currentNode.parentNode;
    }
    return false;
  },

  // 獲取滾動高度
  getScrollTop(element) {
    return 'scrollTop' in element ? element.scrollTop : element.pageYOffset;
  },

  // 設置滾動高度
  setScrollTop(element, value) {
    'scrollTop' in element
      ? (element.scrollTop = value)
      : element.scrollTo(element.scrollX, value);
  },

  // 獲取元素距離頂部高度
  getElementTop(element) {
    return (
      (element === window ? 0 : element.getBoundingClientRect().top) +
      this.getScrollTop(window)
    );
  },

  getVisibleHeight(element) {
    return element === window
      ? element.innerHeight
      : element.getBoundingClientRect().height;
  },

  getComputedStyle:
    !isServer &&
    document.defaultView.getComputedStyle.bind(document.defaultView),
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章