前端黑科技代码

Proud lion 前端 2021-09-03

这里给大家看一下我自己收藏的一些黑科技代码,都是我平常工(mo)作(yu)中看到或者用到的(一般用不到),然后收藏起来(有一些是来自掘金,但是文章我已经找不到,如果作者看到,可以和我说一下,我删了或者把原文链接贴上),那献丑了。

1. 获取当前页面的滚动位置

const getScrollPosition = (el = window) => ({ 
    x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, 
    y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop 
}) 
getScrollPosition(); // {x: 0, y: 200}
复制代码

2. 平滑滚动到页面顶部

const scrollToTop = () => { 
    const c = document.documentElement.scrollTop || document.body.scrollTop 
    if (c > 0) { 
        window.requestAnimationFrame(scrollToTop) window.scrollTo(0, c - c / 8) 
    } 
} 
scrollToTop()
复制代码

3. 确定设备是移动设备还是台式机/笔记本电脑

const detectDeviceType = () => 
    /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i
    .test(navigator.userAgent) ? 
    'Mobile' : 'Desktop' 
detectDeviceType() // "Mobile" or "Desktop"
复制代码

4. 带图带事件的桌面通知

function doNotify(title, options = {}, events = {}) {
  const notification = new Notification(title, options)
  for (let event in events) {
    notification[event] = events[event]
  }
}

function notify(title, options = {}, events = {}) {
  if (!('Notification' in window)) {
    return console.error('This browser does not support desktop notification')
  } else if (Notification.permission === 'granted') {
    doNotify(title, options, events)
  } else if (Notification.permission !== 'denied') {
    Notification.requestPermission().then(function (permission) {
      if (permission === 'granted') {
        doNotify(title, options, events)
      }
    })
  }
}
notify(
  '中奖提示',
  {
    icon: 'https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/f1a9f122e925aeef5e4534ff7f706729~300x300.image',
    body: '恭喜你,掘金签到一等奖',
    tag: 'prize'
  },
  {
    onclick(ev) {
      console.log(ev)
      ev.target.close()
      window.focus()
    }
  }
)
复制代码

5. 数组转树

function treeDataTranslate(data, id = 'id', pid = 'pId') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}
复制代码

6. 禁用在浏览器打开控制台

setInterval(function () {
  check()
}, 4000)
var check = function () {
  function doCheck(a) {
    if (('' + a / a)['length'] !== 1 || a % 20 === 0) {
      ;(function () {}['constructor']('debugger')())
    } else {
      ;(function () {}['constructor']('debugger')())
    }
    doCheck(++a)
  }
  try {
    doCheck(0)
  } catch (err) {}
}
check()
复制代码

7. 函数柯里化

function add() {
  let args = [...arguments]
  function _add() {
      args.push(...arguments)
      return _add
  }
  _add.toString = function () {
      return args.reduce((pre, cur) => {
          return pre + cur
      })
  }
  return _add
}
add(1, 2)(3, 4)(5)(6)()()
复制代码

8. toFullScreen:全屏

function toFullScreen() {
  let elem = document.body
  elem.webkitRequestFullScreen
    ? elem.webkitRequestFullScreen()
    : elem.mozRequestFullScreen
    ? elem.mozRequestFullScreen()
    : elem.msRequestFullscreen
    ? elem.msRequestFullscreen()
    : elem.requestFullScreen
    ? elem.requestFullScreen()
    : alert('浏览器不支持全屏')
}
复制代码

9. exitFullscreen:退出全屏

function exitFullscreen() {
  let elem = parent.document
  elem.webkitCancelFullScreen
    ? elem.webkitCancelFullScreen()
    : elem.mozCancelFullScreen
    ? elem.mozCancelFullScreen()
    : elem.cancelFullScreen
    ? elem.cancelFullScreen()
    : elem.msExitFullscreen
    ? elem.msExitFullscreen()
    : elem.exitFullscreen
    ? elem.exitFullscreen()
    : alert('切换失败,可尝试Esc退出')
}
复制代码

10. 禁止右键、选择、复制

;['contextmenu', 'selectstart', 'copy'].forEach(function (ev) {
  document.addEventListener(ev, function (event) {
    return (event.returnValue = false)
  })
})
复制代码

11. 首字母大写

let firstUpperCase = ([first, ...rest]) => first?.toUpperCase() + rest.join('')
复制代码

12. 数据类型验证

function typeOf(obj) {
  const toString = Object.prototype.toString
  const map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object',
    '[object FormData]': 'formData'
  }
  return map[toString.call(obj)]
}
复制代码

看完后觉得太垃圾,请轻点喷哈,可能是我自己比较菜,才会觉得这些是黑科技。

作者:欢乐症患者

链接:https://juejin.cn/post/7002032291471949838

来源:掘金

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Apipost 私有化火热进行中

评论