el去除某个class

  1. export const removeClass = (el, className) => {
  2. if (!hasClass(el, className)) {
  3. return
  4. }
  5. let reg = new RegExp('(^|\\s)' + className + '(\\s|$)', 'g')
  6. el.className = el.className.replace(reg, ' ')
  7. }

el添加某个class

  1. export const addClass = (el, className) => {
  2. if (hasClass(el, className)) {
  3. return
  4. }
  5. let newClass = el.className.split(' ')
  6. newClass.push(className)
  7. el.className = newClass.join(' ')
  8. }

el是否包含某个class

  1. export const hasClass = (el, className) => {
  2. let reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
  3. return reg.test(el.className)
  4. }

el是否在视口范围内

  1. export const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
  2. const { top, left, bottom, right } = el.getBoundingClientRect();
  3. const { innerHeight, innerWidth } = window;
  4. return partiallyVisible
  5. ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
  6. ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
  7. : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
  8. }

滚动到顶部

  1. export const scrollToTop = () => {
  2. const c = document.documentElement.scrollTop || document.body.scrollTop;
  3. if (c > 0) {
  4. window.requestAnimationFrame(scrollToTop);
  5. window.scrollTo(0, c - c / 8);
  6. }
  7. }

获取滚动的坐标

  1. export const getScrollPosition = (el = window) => ({
  2. x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
  3. y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
  4. });

是否为PC端

  1. export const isPC = () => {
  2. var userAgentInfo = navigator.userAgent;
  3. var Agents = ["Android", "iPhone",
  4. "SymbianOS", "Windows Phone",
  5. "iPad", "iPod"];
  6. var flag = true;
  7. for (var v = 0; v < Agents.length; v++) {
  8. if (userAgentInfo.indexOf(Agents[v]) > 0) {
  9. flag = false;
  10. break;
  11. }
  12. }
  13. return flag;
  14. }

是否是移动端

  1. export const isDeviceMobile = () => {
  2. return /android|webos|iphone|ipod|balckberry/i.test(ua)
  3. }