JS常用方法總結

1、滾動到頁面頂部
const scrollToTop = () => {
	const c = document.documentElement.scrollTop || document.body.scrollTop;
	if (c > 0) {
		// requestAnimationFrame:執行向上滾動動畫
		window.requestAnimationFrame(scrollToTop);
		window.scrollTo(0, c - c / 8);
	}
}

scrollToTop();
2、元素節點是否在可視區域內
const inViewport = (el, partiallyVisible = false) => {
	// 返回元素的大小及其相對於視口的位置
	const { top, left, bottom, right } = el.getBoundingClientRect();
	const { innerHeight, innerWidth } = window;
	return partiallyVisible
		? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
		 	((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
		: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};
// 左右可見
inViewport(node); 
// 全屏(上下左右)可以見
inViewport(node, true); 
3、抽取url中參數
/**
 * 1、match(searchvalue/regexp)
 * 	a、檢索string,返回index等
 *  b、匹配正則,
 * 		在進行正則匹配時,若添加了全局g,那麼會進行全局檢索,若沒有則會匹配一次
 * 2、array.reduce(function(pre, cur, inx, arr){}, initialValue)
 * 	  累加器,	根據某個規則把數組組合成對象
*/
const urlLParams = url =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
    {}
  );
const p1 = urlLParams('https://blog.csdn.net/jiuwanli666?article=166&name=888');
 const p2 = urlLParams('https://blog.csdn.net/jiuwanli666');
4、好描述 => 可讀時間
const formatDuration = ms => {
  if (ms < 0) ms = -ms;
  const time = {
    day: Math.floor(ms / 86400000),
    hour: Math.floor(ms / 3600000) % 24,
    minute: Math.floor(ms / 60000) % 60,
    second: Math.floor(ms / 1000) % 60,
    millisecond: Math.floor(ms) % 1000
  };
	const timeStr = {
		day: '天',
		hour: '小時',
		minute: '分鐘',
		second: '秒',
		millisecond: '毫秒'
	}
	/**
	 * 1、Object.entries(String/Array/Object)
	 * 	返回一個迭代數組(多維數組)
	 * 	子元素是數組,孫元素分別是key/index和value
	 * 	eg:
	 * 		Object.entries('ti')  => [['0', 't'], ['1', 'i']]
	 * 		Object.entries([1,2]) => [['0', 1], ['1', 2]]
	 * 		Object.entries({name: '清雅', gender: 0}) => [['name', '清雅'], ['gender', 0]]
	 * 2、Array方法
	 * 	a、filter,創建一個符合條件的新數組
	 * 		且不會對就數組進行更改
	 * 		eg: [1,2].filter(val => val > 1) => [2]
	 * 	b、map,數組遍歷,組成一個新數組
	 * 		 
	*/
  return Object.entries(time)
    .filter(val => val[1] !== 0)
    .map(([key, val]) => `${val} ${timeStr[key]}`)
    .join('- ');
};
formatDuration(new Date().getTime())
// 18347 天- 3 小時- 39 分鐘- 56 秒- 248 毫秒
5、複製文本信息
/**
 * 思路:
 * 		創建一個只讀的文本域
 *
 * 1、getSelection
 * 		表示用戶選擇的文本範圍或者光標的當前位置
 * 2、execCommand
 * 		允許運行命令來操縱可編輯區域的元素
 */
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);
	 }
};
6、計數器
const counter = (selector, start, end, step = 1, duration = 2000) => {
	let current = start,
		_step = (end - start) * step < 0 ? -step : step,
		timer = setInterval(() => {
			current += _step;
			document.querySelector(selector).innerHTML = current;
			if (current >= end) clearInterval(timer);
		}, Math.abs(Math.floor(duration / (end - start))));
	return timer;
};
// 事例
counter('.box', 1, 1000, 5, 2000); 
7、
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章