Check the distance of the scroll bar

Conventional: window. PageXOffset/pageYOffset (ie 9 some version of Internet explorer does not support “) Internet explorer 9, 8, and the following: document. Body. ScrollLeft/document. The body. The scrollTop

Encapsulate compatibility functions for getting scrollbar distance

function getScrollOffset() {
  if(window.pageXOffset) {
    return {
      left: window.pageXOffset,
      top: window.pageYOffset
    }
  }else {
    return {
      left: document.body.scrollLeft + document.documentElement.scrollLeft,
      top: document.body.scrollTop + document.documentElement.scrollTop 
    }
  }
}
Copy the code

Browser weird mode and standard mode

Weird mode: BackCompat Standard mode: CSS1Compat

The size of the viewable area of the browser window (excluding the browser’s own UI bar)

General: window. InnerWidth/innerHeight

IE9/IE8 and below:

Standard mode: the document. The documentElement. ClientWidth/clientHeight

Quirks mode: the document body. ClientWidth/clientHeight

Encapsulate the function that gets the browser’s visual window size

    function getViewportSize() {
      if(window.innerWidth) {
        return {
          width: window.innerWidth,
          height: window.innerHeight
        }
      }else {
        if(document.compatMode === 'BackCompat') {
          return {
            width: document.body.clientWidth,
            height: document.body.clientHeight
          }
        }else {
          return {
            width: document.documentElement.clientWidth,
            height: document.documentElement.clientHeight
          }
        }
      }
    }
Copy the code

GetBoundingClientRect () can get the size and coordinates of the element, but not in real time. Besides, width and height can be calculated using the padding value

Element position

OffsetTop /offsetLeft(the calculated value depends on whether the parent is positioned or not, and includes its own margin,padding, and top values)

OffsetParent returns a positioned parent element

// A function wrapper that gets the distance between the element and the left and top edges of the outermost element HTML
function getElementDocPosition(el) {
  var parent = el.offsetParent,
      offsetLeft = el.offsetLeft,
      offsetTop = el.offsetTop;
  while(parent) {
    offsetLeft += parent.offsetLeft;
    offsetTop += parent.offsetTop;
    parent = parent.offsetParent;
  }

  return {
    left: offsetLeft,
    top: offsetTop
  }
}
Copy the code

Window. The scroll/window. ScrollTo, window scrollBy (each will continue rolling distance, on the basis of the original can be negative)