整理收集前端常用的一些代码段

文章目录

判断多个时间区间是否有交叉

// 基于moment
function iscover(dates){ 
	for (var i = 0; i < dates.length; i++) { 
	    for (var j = 0; j < dates.length; j++) { 
	        if (i != j) { 
	            if (
	                moment(dates[j][0]).isBetween(dates[i][0], dates[i][1]) ||
	                moment(dates[j][0]).isSame(dates[i][0]) ||
	                moment(dates[j][0]).isSame(dates[i][1]) ||
	                moment(dates[j][1]).isBetween(dates[i][0], dates[i][1]) ||
	                moment(dates[j][1]).isSame(dates[i][0]) ||
	                moment(dates[j][1]).isSame(dates[i][1])
	            ) { 
	                return {  i:i, j:j };
	            }
	        }
	    }
	}
	return true;
}

var dateArr = [
	['2021-06-03','2021-06-05'],
	['2021-06-06','2021-06-08'],
	['2021-06-04','2021-06-05']
]
var c = iscover(dateArr)
if(c!==true){ 
	console.log(`${ c.i}${ c.j}交叉哦!`); // 0和2交叉哦!
}

A追逐B(点A向点B靠近)

// aim趋向cur,一般用来做鼠标跟随.
function lerpDistance(aim, cur, ratio) { 
	var delta = cur - aim;
	return aim + delta * ratio;
}

document.addEventListener('mousemove',mouseMove)
var x = 350,y = 350;
function mouseMove(e) { 
	if (e.offsetX || e.layerX) { 
		var px = e.offsetX == undefined ? e.layerX : e.offsetX;
		var py = e.offsetY == undefined ? e.layerY : e.offsetY;
		if(px>=0 && px<=700&& py>=0 && py<=700) { 
			x = lerpDistance(x, px, 0.3);
			y = lerpDistance(y, py, 0.3);
		}
	}
}

获取随机数区间

 function rangeRandom (m,n){ 
  return Math.floor(Math.random()*(m - n) + n);
}
// 获取100-600中间的随机数
console.log(rangeRandom(100, 600))

角度b趋向角度a

function lerpAngle(a, b, t) { 
	var d = b - a;
	if (d > Math.PI) d = d - 2 * Math.PI;
	if (d < -Math.PI) d = d + 2 * Math.PI;
	return a + d * t;
}

document.addEventListener('mousemove',mouseMove)
var x = 350,y = 350,angle = 0;
function mouseMove(e) { 
  if(e.layerX>=0 && e.layerX<=700&& e.layerY>=0 && e.layerY<=700) { 
  	var _angle = Math.atan2(y-e.layerY ,x-e.layerX); // 计算(x,y)点到鼠标当前的点的角度
   	angle = lerpAngle( _angle, angle  , .3); // angle向_angle靠拢
  	rotate(angle); // 旋转这个角
  }
}

简单的碰撞检测

// 点(x1,y2)和点(x2,y2)之间的距离的平方
function calLength(x1, y1, x2, y2) { 
	return Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2);
}
// 以点(1,1)为中心画了个圆圈,半径为2,以点(5,6)为中心画了个圆圈,半径为3
var len = calLength(1, 1, 5, 6); 
if(len <= (2+3) * (2+3)){  console.log('碰撞到一起啦!') }

el中是否包含classname

const hasClass = (el: Element, className: string) => el.classList.contains(className);

判断el上有没有className,有的话就移除,没有的话就添加上

const toggleClass = (el: Element, className: string) => el.classList.toggle(className); 

xpath获取单个element

const getElementByPath = (path: string) => return document.evaluate(path, document).iterateNext();

xPath获取element集合

  const getElementsByPath = (path: string) => { 
    const result = document.evaluate(path, document, null, XPathResult.ANY_TYPE, null);
    const ret = [];
    let nodes = result.iterateNext();
    if (nodes) { 
        ret.push(nodes)
    }
    while (nodes) { 
        nodes = result.iterateNext();
        if (nodes) { 
            ret.push(nodes)
        }
    }
    return ret;
  }

反向获取xPath路径

    function readXPath(element) { 
      if (element.id !== "") { 
        return '//*[@id="' + element.id + '"]';
      }
      if (element == document.body) { 
        return "/html/" + element.tagName.toLowerCase();
      }
      let x = 1, siblings = element.parentNode.childNodes; //同级的子元素
      for (let i = 0, l = siblings.length; i < l; i++) { 
        const sibling = siblings[i];
        if (sibling == element) { 
          if (element.parentNode) { 
            return readXPath(element.parentNode) + "/" + element.tagName.toLowerCase() + "[" + x + "]"  
          }
        } else if ( sibling.nodeType == 1 && sibling.tagName == element.tagName ) { 
          x++;
        }
      }
    }

父节点parent中是否存在子节点 child

const inNode = (child: Element, parent: Element) => parent !== child && parent.contains(child);

隐藏element

const hideEl = (...el) => [...el].forEach(e => (e.style.display = 'none'));
hideEl(document.querySelectorAll('span'));

获取一个元素内的所有图像

const getImages = (el, includeDuplicates = false) => { 
  const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src'));
  return includeDuplicates ? images : [...new Set(images)];
};
getImages(document, true); // ['image1.jpg', 'image2.png', 'image1.png', '...']
getImages(document, false); // ['image1.jpg', 'image2.png', '...']

添加一个元素的事件侦听器

const addEvent = (el, eventType, fn) => el.addEventListener(eventType, fn)

移除一个元素的事件侦听器

const removeEvent = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts);

const fn = () => console.log('!');
addEvent(document.getElementById('box'), 'left', fn)
removeEvent(document.getElementById('box'), 'left', fn);

在给定元素上触发特定事件,且可选传递自定义数据

const triggerEvent = (el, eventType, detail) => el.dispatchEvent(new CustomEvent(eventType, {  detail }));

//document.getElementById('box').addEventListener('left', (e) => {});
triggerEvent(document.getElementById('box'), 'left');
triggerEvent(document.getElementById('box'), 'left', {  arg: 'hehe' });

确认指定元素是否在视口可见

const elementIsVisibleInViewport = (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;
};
elementIsVisibleInViewport(el); // (不完全可见)
elementIsVisibleInViewport(el, true); // (部分可见)

获取当前页面的滚动位置

const getScroll = (el = window) => ({ 
  x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
  y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});

平滑滚动到页面顶部

const animateScrollToTop = () => { 
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) { 
    window.requestAnimationFrame(animateScrollToTop);
    window.scrollTo(0, c - c / 8);
  }
};

获取浏览器的 URL

window.location.href;  // 'https://baidu.com'

创建一个包含当前 URL 参数的对象

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

getURLParameters('http://fanjiaxing.com/home?a=age&s=sex'); // {a: 'age', s: 'sex'}
getURLParameters('baidu.com'); // {}

对传递的 URL 进行 GET 请求

const httpGet = (url, callback, err = console.error) => { 
  const request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.onload = () => callback(request.responseText);
  request.onerror = () => err(request);
  request.send();
};
httpGet(
  'https://jsonplaceholder.typicode.com/posts/1',
  console.log
); 
// Logs: {"userId": 1, "id": 1, "title": "sample title", "body": "my text"}

对传递的 URL 进行 POST 请求

const httpPost = (url, data, callback, err = console.error) => { 
  const request = new XMLHttpRequest();
  request.open('POST', url, true);
  request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
  request.onload = () => callback(request.responseText);
  request.onerror = () => err(request);
  request.send(data);
};
const newPost = { 
  userId: 1,
  id: 1337,
  title: 'Foo',
  body: 'bar bar bar'
};
const data = JSON.stringify(newPost);
httpPost(
  'https://jsonplaceholder.typicode.com/posts',
  data,
  console.log
); 
// Logs: {"userId": 1, "id": 1337, "title": "Foo", "body": "bar bar bar"}

分辨设备是移动设备还是桌面设备

const detectDeviceType = () =>
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
    ? 'Mobile'
    : 'Desktop';

detectDeviceType(); // "Mobile" or "Desktop"

获取两个日期之间的天数间隔

const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
  (dateFinal - dateInitial) / (1000 * 3600 * 24);

getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9

将一组表单元素编码为一个对象

const formToObject = form =>
  Array.from(new FormData(form)).reduce(
    (acc, [key, value]) => ({ 
      ...acc,
      [key]: value
    }),
    { }
  );

formToObject(document.querySelector('#form')); // { email: 'test@email.com', name: 'Test Name' }

从对象中检索给定选择器指示的一组属性

const get = (from, ...selectors) =>
  [...selectors].map(s =>
    s
      .replace(/\[([^\[\]]*)\]/g, '.$1.')
      .split('.')
      .filter(t => t !== '')
      .reduce((prev, cur) => prev && prev[cur], from)
  );
const obj = {  selector: {  to: {  val: 'val to select' } }, target: [1, 2, {  a: 'test' }] };

get(obj, 'selector.to.val', 'target[0]', 'target[2].a'); // ['val to select', 1, 'test']

在等待一定时间后调用提供的函数(单位毫秒)

const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args);
delay(
  function(text) { 
    console.log(text);
  },
  1000,
  'later'
); 
// 一秒后记录 'later' 。

获得给定毫秒数的可读格式

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
  };
  return Object.entries(time)
    .filter(val => val[1] !== 0)
    .map(([key, val]) => `${ val} ${ key}${ val !== 1 ? 's' : ''}`)
    .join(', ');
};

formatDuration(1001); // '1 second, 1 millisecond'
formatDuration(34325055574); // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'

为指定选择器创建具有指定范围、步长和持续时间的计时器

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) document.querySelector(selector).innerHTML = end;
      if (current >= end) clearInterval(timer);
    }, Math.abs(Math.floor(duration / (end - start))));
  return timer;
};

counter('#my-id', 1, 1000, 5, 2000); // 为 id="my-id" 的元素创建一个两秒的计时器

将一个字符串复制到剪贴板

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);
  }
};

copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.

确定页面的浏览器选项卡是否处于前台活跃状态

const isBrowserTabFocused = () => !document.hidden;

isBrowserTabFocused(); // true

当其选项卡的内容变得可见或被隐藏

function fn(){ 
	console.log('哎呀,你刚才是不是按了手机物理键退出啦!')
}
window.addEventListener('visibilitychange', fn);
window.removeEventListener('visibilitychange', fn);

数组里面对象去重

let newobj = { }; 
arr = arr .reduce((preVal, curVal) => { 
	newobj[curVal.id] ? '' : newobj[curVal.id] = preVal.push(curVal); 
	return preVal 
}, [])

将tree深层嵌套结构的数据,重新组织或者拉平

export class FileNode { 
  treeChildren: FileNode[];
  treeFilename: string;
  treeType: any;
  [key: string]: any;
}
 
export class FileFlatNode { 
  [key: string]: any;
  constructor(
    public treeExpandable: boolean, public treeFilename: string, public treeLevel: number, public treeType: any 
  ) { 
  }
}
 
// 将数据重新组织成一个嵌套的tree
export const buildFileTree = (arr: any[]): FileNode[] => { 
  return arr.reduce((pre, cur, index, arr) => { 
    const node = new FileNode();
    node.treeFilename = cur.Name;
    for (const key in cur) { 
      if (key !== 'ChildNode') { 
        node[key] = cur[key];
      }
    }
    if (cur.ChildNode && cur.ChildNode.length) { 
      node.treeChildren = buildFileTree(cur.ChildNode);
    }
    return pre.concat(node); // 将node合并到上一个pre数组中
  }, []); // pre 的初始值为[]
};
 
// 将数据重新组织,将子节点取出来放在和父节点平衡的数组里面,拉平成一个不嵌套的tree
export const buildFileFlatTree = (arr: any[], level: number, type: any = null): FileFlatNode[] => { 
  return arr.reduce((pre, cur, index, arr) => { 
 
    const node = new FileFlatNode(!!cur.ChildNode, cur.name, level, type);
	node.treeLevel = level;
    for (const key in cur) { 
      if (key !== 'ChildNode') { 
        node[key] = cur[key];
      }
    }
    let _pre = pre.concat(node);
    if (cur.ChildNode && cur.ChildNode.length) { 
      _pre = _pre.concat(buildFileFlatTree(cur.ChildNode, level + 1, cur.name));
    }
    return _pre;
  }, []);
};

根据子元素的guid获取所有父级的guid

// 逆序,获取当前部门的所有父元素的guid
function getParentsId(arr, PK_Guid) { 
    var idArr = [];
    var fns = function(arr){ 
        for (const item of arr) { 
            if (item.PK_Guid == PK_Guid) { 
                idArr.push(item.PK_Guid);
                break;
            }
            if (item.ChildNode) { 
                if (JSON.stringify(item.ChildNode).match(PK_Guid)) { 
                    idArr.push(item.PK_Guid);
                }
                fns(item.ChildNode);
            }     
        }
    }
    fns(arr)
    return idArr;
}

根据id获取当前架构信息以及下级信息

function getOneInfo(data,id){ 
	let obj = null;
	function fn(data,id){ 
		for(const item of data){ 
			if(item.PK_Guid === id){ 
				obj = item;
				break;
			}
			if(item.ChildNode&&item.ChildNode.length){ 
				fn(item.ChildNode,id)
			}
		}
	}
	fn(data,id);
	return obj;
}

get set

 function Picker() { 
 	this._day = 30; 
 }

 Picker.prototype = { 
     get day() { 
         return this._day;
     },
     set day(day) { 
         this._day = day;
     }
 }

http-server搭建本地服务器

1. npm install http-server -g
2. 进入目录,运行http-server即可
    原文作者:榴莲不好吃
    原文地址: https://blog.csdn.net/l284969634/article/details/118055327
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞