几个解决实际问题的ES6代码段

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';  
    // Example  
detectDeviceType(); // "Mobile" or "Desktop"

4、如何将一个字符串复制到剪贴板?

const copyToClipboard = str => {  
      const el = document.createElement('textarea');  
      el.value = str;  
      el.setAttribute('readonly', '');  
      el.style.position = 'absolute';  
      el.style.left = '-9999px';  
      document.body.appendChild(el);  
      const selected =  
        document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;  
      el.select();  
      document.execCommand('copy');  
      document.body.removeChild(el);  
      if (selected) {  
        document.getSelection().removeAllRanges();  
        document.getSelection().addRange(selected);  
      }  
    };  
// Example  
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.

完结

2020-11-05 15:57:59

原文地址:https://www.cnblogs.com/chailuG/p/13932175.html