常用的JS方法

149 阅读1分钟

1. navigator.clipboard 实现复制粘贴功能

复制功能的实现

const copyText = async (text) => {
  try {
    await navigator.clipboard.writeText(text);
    console.log('复制成功!');
  } catch (err) {
    console.error('无法复制: ', err);
  }
};

粘贴功能的实现

const pasteText = async () => {
  try {
    const text = await navigator.clipboard.readText();
    console.log('粘贴成功: ', text);
  } catch (err) {
    console.error('无法粘贴: ', err);
  }
};

此时,为了兼容,我们可以在代码里加一个Permissions API的判断, 例如:

if (navigator.clipboard && navigator.permissions) { 
    await navigator.clipboard.writeText(val) 
}

2. indexOf 第二个参数有什么作用?

参数

  • searchElement

    数组中要查找的元素。

  • fromIndex 可选

    开始搜索的索引(从零开始),会转换为整数

    • 负索引从数组末尾开始计数——如果 frommindex < 0,使用 frommindex + array.length。注意,在这种情况下,仍然从前到后搜索数组。
    • 如果 fromIndex < -array.length 或者省略了 fromIndex ,将使用 0,而导致整个数组被搜索。
    • 如果 fromIndex >= array.length,数组不会继续搜索并返回 -1

3. 向下滚动加载更多

const yiShengGLEl = document.querySelector('.scrollbar__wrap')
if (yiShengGLEl) {
  const that = this
  yiShengGLEl.addEventListener('scroll', debounce(function(e) {
    const bottomOffset = 10;
    if (this.scrollHeight - this.scrollTop <= this.clientHeight + bottomOffset) {
      console.log('接近容器底部');
      that.loadMore()
    }
  }, 300))