成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

16 個日常開發必備的 JavaScript 代碼片段

開發 前端
在 Web 開發領域,開發效率是關鍵。為什么每次開始新項目時都要重新發明輪子?今天,本文匯總整理了一些方便日常開發使用的 JavaScript 代碼片段,超越了 Lodash 和 day.js 等常見代碼片段,提升你的開發效率,減少工作時長。

在 Web 開發領域,開發效率是關鍵。為什么每次開始新項目時都要重新發明輪子?今天,本文匯總整理了一些方便日常開發使用的 JavaScript 代碼片段,超越了 Lodash 和 day.js 等常見代碼片段,提升你的開發效率,減少工作時長。

讓我們開始吧!

1. 檢測元素外的點擊 

厭倦了復雜的檢查以查看點擊是否落在目標元素之外?使用 contains 方法簡化事情,以更簡潔的方式隱藏模式或折疊菜單:

document.addEventListener('click', function (evt) {
     // isClickedOutside is true if the clicked element is outside 'ele'
     const isClickedOutside = !ele.contains(evt.target);
   });

2. 快速打開官方網站 

需要查閱第三方庫的文檔或存儲庫?這些命令將快速帶您到達那里:

# Open the homepage
   npm home PACKAGE_NAME
   npm home react


# Open the repository
   npm repo PACKAGE_NAME
   npm repo react

3. 一次性事件監聽器 

對于只想處理一次的事件,可以利用 once 選項,而不是手動刪除監聽器:

const handler = function (e) {};
   ele.addEventListener('event-name', handler, { once: true });

4. 將秒數格式化為 HH:mm:ss 

顯示音頻或視頻的時長時,以用戶友好的 HH:mm:ss 格式顯示秒數:

const formatSeconds = (s) =>
     [parseInt(s / 60 / 60), parseInt((s / 60) % 60), parseInt(s % 60)]
       .join(':')
       .replace(/\b(\d)\b/g, '0$1')

對于相對時間顯示,如“幾秒前”或“5 分鐘前”,請探索 timeago.js 庫!

5. 將 URL 參數轉換為對象 

雖然 query-string 是一個流行的庫,但可以直接使用 URLSearchParams API 實現相同的功能:

const getUrlParams = (query) =>
     Array.from(new URLSearchParams(query)).reduce(
       (p, [k, v]) =>
         Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }),
       {}
     )


// Get query parameters
   getUrlParams(location.query)
   // { a: ['1', '4'], b: '2', c: '3' }
   getUrlParams('?a=1&b=2&c=3&a=4') 
   // Get hash parameters
   getUrlParams(location.hash.split('?')[1])

6. 安全打開新標簽頁 

打開新標簽頁看似微不足道,但需要注意安全。在外部鏈接時,使用 noopener noreferrer 來防止惡意網站通過 window.opener.location 重定向您的網站。這同樣適用于 window.open。

<a target="_blank" rel="noopener noreferrer">...</a>


// window.open defaults rel to 'opener', so set it explicitly
   window.open('https://google.com', 'google', 'noopener,noreferrer')

警告:以下代碼片段存在安全漏洞!

<a target="_blank" rel="opener">
...</a>
window.opener.location = 'http://fake.website.here';

7. 預覽上傳的圖像 

使用 FileReader API 直接在瀏覽器中顯示用戶上傳圖像的預覽:

function readImage() {
     const fileReader = new FileReader()
     const file = document.getElementById('uploaded-file').files[0]


    if (file) {
       fileReader.readAsDataURL(file)
     }


     fileReader.addEventListener(
       'load',
       () => {
         const result = fileReader.result
         const resultContainer = document.getElementById('result')
         const img = document.createElement('img')
         img.src = result
         resultContainer.append(img)
       },
       { once: true }
     )
   }

8. 下載文件 

使用 <a> 標簽的下載屬性觸發下載。請記住,這對于同源文件可靠地起作用,并且在 IE 和移動設備上可能會受到限制:

<a href="/path/to/file" download>Download</a>

或者,使用 JavaScript 生成臨時的 <a> 標簽:

function download(url) {
     const link = document.createElement('a')
     link.download = 'file name'
     link.href = 'url'


     document.body.appendChild(link)
     link.click()
     document.body.removeChild(link)
}

對于靜態文件,在服務器上設置適當的 Content-Disposition 標頭也可以觸發下載:

Content-Disposition: attachment; filename="filename.jpg"

除了文件下載之外,還可以使用 Blob 對象和 createObjectURL 方法創建和下載文本或 JSON 文件:

const data = JSON.stringify({ 'message': 'Hello Word' });


const blob = new Blob([data], { type: 'application/json' });
 // Create a URL for the blob
 const url = window.URL.createObjectURL(blob);
 // Download the URL using the 'download' function above
 ...


 // Release the URL object
 window.URL.revokeObjectURL(url);

9. 記憶函數結果 

使用記憶法緩存計算量大的函數的結果:

const memoize = (fn) =>
     (
       (cache = Object.create(null)) =>
       (arg) =>
         cache[arg] || (cache[arg] = fn(arg))
     )()

10. 多行省略號...

使用 CSS 用省略號截斷文本內容,無論是單行還是多行:

.truncate {
     overflow: hidden;
     text-overflow: ellipsis;
     white-space: nowrap;
   }


.truncate-multi {
     display: -webkit-box;
     -webkit-box-orient: vertical;
     -webkit-line-clamp: 2; 
     overflow: hidden;
   }

11. 使用 CSS 選擇最后 N 個元素 

使用 CSS 選擇器定位列表中的最后幾個元素:

// First three items
   li:nth-child(-n + 3) {
     text-decoration: underline;
   }


// Items 2 through 5
   li:nth-child(n + 2):nth-child(-n + 5) {
     color: #2563eb; 
   } 
   // Last two items
   li:nth-last-child(-n + 2) {
     text-decoration: line-through; 
   }

12. 自定義滾動條樣式 

增強滾動條的外觀和感覺:

::-webkit-scrollbar {
   width: 8px;
   height: 8px; 
}


::-webkit-scrollbar-track {
   border-radius: 10px;
   background-color: #fafafa; 
}


::-webkit-scrollbar-thumb {
   border-radius: 10px;
   background: rgb(191, 191, 191); 
}
/* Modern scrollbar API */
body {
   scrollbar-width: thin; 
   scrollbar-color: #718096 #edf2f7; 
}

請記住,滾動條樣式也可以使用 better-scroll 等庫來實現更高級的自定義。

13. 使用最大余數法精確計算百分比 

使用百分比時,四舍五入有時會導致總數不完全等于 100%。使用最大余數法進行準確分配:

// Outputs:  ['32.56%', '6.97%', '27.91%', '32.56%'] 
  getPercentWithPrecision([56, 12, 48, 56], 2)


function getPercentWithPrecision(valueList, precision) {
    const digits = Math.pow(10, precision)
    const sum = valueList.reduce((total, cur) => total + cur, 0)


    const votesPerQuota = valueList.map((val) => {
        return val / sum * 100 * digits
    })
    const seats = votesPerQuota.map((val) => {
      return Math.floor(val);
    });
    const remainder = votesPerQuota.map((val) => {
      return val - Math.floor(val)
    })


    let totalSeats = 100 * digits
    let currentSeats = votesPerQuota.reduce((total, cur) => total + Math.floor(cur), 0)


    while(totalSeats - currentSeats > 0) {
      let maxIdx = -1 
      let maxValue = Number.NEGATIVE_INFINITY 
      for(let i = 0; i < remainder.length; i++) {
        if (maxValue < remainder[i]) {
          maxValue = remainder[i]
          maxIdx = i
        }
      }


      seats[maxIdx]++
      remainder[maxIdx] = 0
      currentSeats++
    }


    return seats.map((val) => `${val / totalSeats * 100}%`)
  }

14. 限制并發請求 

處理大量請求時,管理并發以防止服務器不堪重負:

async function asyncPool(poolLimit, iterable, iteratorFn) {
    const ret = [];
    const executing = new Set();
    for (const item of iterable) {
      const p = Promise.resolve().then(() => iteratorFn(item, iterable));
      ret.push(p);
      executing.add(p);
      const clean = () => executing.delete(p);
      p.then(clean).catch(clean);
      if (executing.size >= poolLimit) {
        await Promise.race(executing);
      }
    }
    return Promise.all(ret);
  }


// Example usage 
  const timeout = i => new Promise(resolve => setTimeout(() => resolve(i), i));
  asyncPool(2, [1000, 5000, 3000, 2000], timeout).then(results => {
    console.log(results)
  })

15. 生成 UUID 

創建通用唯一標識符:

const uuid = (a) =>
    a
      ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16)
      : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid)

16. 在模態框打開時禁用正文滾動 

在模態框打開時防止背景內容滾動:

// Disable body scrolling 
  document.body.style.overflow = 'hidden';


// Re-enable scrolling
  document.body.style.removeProperty('overflow');

總結

以上就是我今天想與你分享的16個日常開發中會經常遇到的一些功能需求,希望通過閱讀本文內容能夠對你有所幫助,如果你還有其他問題,請在留言區給我留言,我們一起交流學習進步。

責任編輯:華軒 來源: web前端開發
相關推薦

2022-06-26 09:56:50

HttpUtil工具類模式

2021-09-03 10:08:53

JavaScript開發 代碼

2023-05-17 08:34:27

開發技術應用

2011-09-06 15:16:42

PHP

2021-08-03 15:26:56

代碼智能阿里云

2023-03-26 07:58:04

開發工具開源

2017-09-06 12:42:45

AndroidGradle開發技巧

2023-10-10 16:16:05

JavaScrip開發

2023-10-09 14:48:06

2023-05-22 15:53:06

JavaScrip代碼素材

2011-07-11 10:16:07

JavaScript

2022-07-06 08:39:33

Python代碼

2024-06-21 11:02:16

2021-10-29 11:05:34

JavaScript代碼字符串

2023-12-26 14:28:08

JavaScript開發

2023-06-16 16:34:25

JavaScripWeb 開發

2023-11-03 16:02:00

JavaScript開發

2024-01-04 16:46:58

JavaScript開發

2017-01-10 19:06:39

Android日常開發技術經驗

2022-09-16 09:11:30

C++代碼編程
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: a视频在线观看 | 亚洲一区欧美一区 | 久久成人精品一区二区三区 | av中文在线播放 | 精品久久久久久久 | 国产精品毛片无码 | 亚洲最大的成人网 | 性一交一乱一透一a级 | 久久精品国产99国产精品 | 日本一区视频在线观看 | 中文字幕在线免费观看 | 精品日韩一区 | 欧美视频区 | 亚洲一区二区三区免费视频 | 国产高清在线观看 | 99久久精品免费看国产四区 | www.日日夜夜| 精品成人一区二区 | 成人在线 | 在线精品亚洲欧美日韩国产 | 国产视频第一页 | 嫩草视频在线 | 日韩精品久久一区 | 国产精品99久久久久久动医院 | 国产成人精品免费视频大全最热 | 亚洲精品视频观看 | a网站在线观看 | 欧美一区二区三区的 | 男女一区二区三区 | 国产成人精品一区二区三区在线观看 | 久草院线 | 亚洲a毛片| 这里只有精品999 | 日韩欧美网| 久久中文字幕一区 | www.成人在线视频 | 欧美日韩精品中文字幕 | 九九热精品在线视频 | 亚洲精品视频导航 | 日韩a在线 | 综合久久久 |