一些JavaScript函数

1、生成随机颜色

const generateRandomHexColor=()=>`#${Math.floor(Math.random() * 0xffffff).toString(16)}`
console.log(generateRandomHexColor())

2、数组重排序

const shuffle=(arr)=>arr.sort(()=>Math.random()-0.5)
const arr=[1,2,3,4,5]
console.log(shuffle(arr))

3、复制到剪切板

const copyToClipboard = (text) => navigator.clipboard && navigator.clipboard.writeText && navigator.clipboard.writeText(text)
copyToClipboard("Hello World!")

4、滚动到顶部

将元素滚动到顶部最简单的方法是使用scrollIntoView。设置block为start可以滚动到顶部;设置behavior为smooth可以开启平滑滚动

const scrollToTop = (element) => element.scrollIntoView({ behavior: "smooth", block: "start" });

5、滚动到底部

const scrollToBottom = (element) => element.scrollIntoView({ behavior: "smooth", block: "end" });

6、检测元素是否在屏幕中

使用的方法是IntersectionObserver

const callback = (entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      // `entry.target` is the dom element
      console.log(`${entry.target.id} is visible`);
    }
  });
};

const options = {
  threshold: 1.0,
};
const observer = new IntersectionObserver(callback, options);
const btn = document.getElementById("btn");
const bottomBtn = document.getElementById("bottom-btn");
observer.observe(btn);
observer.observe(bottomBtn);

7、检测设备

const detectDeviceType = () =>
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  ) ? "Mobile" : "Desktop";

console.log(detectDeviceType());

8、隐藏元素

const hideElement = (el, removeFromFlow = false) => {
  removeFromFlow ? (el.style.display = 'none')
  : (el.style.visibility = 'hidden')
}

9、从url中获取参数

const getParamByUrl = (key) => {
  const url = new URL(location.href)
  return url.searchParams.get(key)
}

10、等待函数

const wait = (ms) => new Promise((resolve)=> setTimeout(resolve, ms))

const asyncFn = async () => {
  await wait(1000)
  console.log('等待异步函数执行结束')
}

asyncFn()

 

 

原文来自:https://juejin.cn/post/7127278574033174542

 

posted @ 2022-08-09 16:05  超哥20  阅读(23)  评论(0编辑  收藏  举报