JavaScript常用小技巧

1、获取地址栏参数 URL URLSearchParams

const url = new URL("https://www.baidu.com?_t=123&search=今天&n=1&limit=10");

const params =new URLSearchParams(url.search);
// 或 const params =new URLSearchParams(window.location.search);
console.log('_t:',params.get('_t'))
console.log('search:',params.get('search'))
console.log('n:',params.get('n'))
console.log('limit:',params.get('limit'))

// 输出结果
// _t: 123
// search: 今天
// n: 1
// limit: 10

2、获取地址栏参数,并且转 JSON 格式 Object.fromEntries

// 转 JSON 格式
const parse = (queryString) => {
    return Object.fromEntries(new URLSearchParams(queryString));
};

console.log(parse(url.search))

// 输出
{_t: '123', search: '今天', n: '1', limit: '10'}

// 第二种
const getURLParameters = url =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => (
      (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a
    ),
    {}
  );

getURLParameters('google.com'); // {}
getURLParameters('http://url.com/page?name=Adam&surname=Smith');
// {name: 'Adam', surname: 'Smith'}

 3、使用 fetch 发起一个 get 请求 并且携带参数

const fetchTianQi = ({ page, size, location }) => {
    return fetch(
        `https://v-api.2345.com/shortVideo/api/GetListByLocation?${new URLSearchParams({
            page,
            size,
            location,
        })}`
    );
};
// 可以这样
const fetchTianQi = (data) => {
    return fetch(
        `https://v-api.2345.com/shortVideo/api/GetListByLocation?${new URLSearchParams(data)}`
    );
};

await fetchTianQi({
    page: 1,
    size: 100,
    location: 'tianqihome-shortMovie',
});

// 输出
Response {type: 'cors', url: 'https://v-api.2345.com/shortVideo/api/GetListByLoc…on?page=1&size=100&location=tianqihome-shortMovie', redirected: false, status: 200, ok: true, …}

 4、获取鼠标位置

document.addEventListener('mousemove', (e) => {
    console.log(`Mouse X: ${e.clientX}, Mouse Y: ${e.clientY}`);
});

5、拷贝内容到剪切板 navigator.clipboard.writeText

const copyToClipboardAsync = str => {
    if (navigator && navigator.clipboard && navigator.clipboard.writeText)
        return navigator.clipboard.writeText(str);
    return Promise.reject('剪贴板API不可用。');
};
// 示例
copyToClipboardAsync('你一定可以的');
// 第二种实现
const  copyToClipboard  = text => {
        var input = document.createElement("textarea");
        input.value = text;
        document.body.appendChild(input);
        input.select();
        document.execCommand("copy");
        document.body.removeChild(input);
 }
copyToClipboard('你一定可以的');

6、滚动到页面顶部 window.scrollTo

const scrollToTop = () => {
  window.scrollTo({ top: 0, left: 0, behavior: "smooth" });
};

 7、滚动到页面底部

const scrollToBottom = () => {
  window.scrollTo({
    top: document.documentElement.offsetHeight,
    left: 0,
    behavior: "smooth",
  });
};

8、判断当前设备是 Android 还是 iOS

const isAndroid = () =>/android/i.test(navigator.userAgent.toLowerCase());

const isIOS = () => /iPhone|iPad|iPod|iOS|Macintosh/i.test(navigator.userAgent.toLowerCase());

 9、移除 dom 监听事件

const off = (el, evt, fn, opts = false) =>{
 el.removeEventListener(evt, fn, opts);
}
// 示例
const fn = () => console.log('!');
document.body.addEventListener('click', fn);
off(document.body, 'click', fn);

 10、批量添加 dom 事件

const addMultipleListeners = (el, types, listener, options, useCapture) => {
  types.forEach(type =>
    el.addEventListener(type, listener, options, useCapture)
  );
};
// 批量添加事件
addMultipleListeners(
  document.querySelector('.my-element'),
  ['click', 'mousedown'],
  () => { console.log('hello!') }
);

 11、dom 事件只执行一次 addEventListener

const listenOnce = (el, evt, fn) =>{
  el.addEventListener(evt, fn, { once: true });
}

12、地址栏参数拼接

const query = "Where's Waldø?";
const locale = "en-US";
const campaign = "promo_email";

// Good
const url = new URL('https://examp.le');

url.searchParams.set('q', query);
url.searchParams.set('lang', locale);
url.searchParams.set('from', campaign);

url.toString();
// 'https://examp.le/?q=Where%27s+Wald%C3%B8%3F&lang=en-US&from=promo_email'

 

posted @ 2023-03-17 16:19  天葬  阅读(21)  评论(0编辑  收藏  举报