当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 24个ES6方法解决JS实际开发问题(小结)

24个ES6方法解决JS实际开发问题(小结)

2020年06月14日  | 移动技术网IT编程  | 我要评论

本文主要介绍 24 中 es6 方法,这些方法都挺实用的,本本请记好,时不时翻出来看看。

1、如何隐藏所有指定的元素:

const hide = (el) => array.from(el).foreach(e => (e.style.display = 'none'));

// 事例:隐藏页面上所有`<img>`元素?
hide(document.queryselectorall('img'))

2、如何检查元素是否具有指定的类 ?
页面dom里的每个节点上都有一个 classlist 对象,程序员可以使用里面的方法新增、删除、修改节点上的css类;使用 classlist,程序员还可以用它来判断某个节点是否被赋予了某个css类;

const hasclass = (el, classname) => el.classlist.contains(classname)

// 事例
hasclass(document.queryselector('p.special'), 'special') // true

3.如何切换一个元素的类 ?

const toggleclass = (el, classname) => el.classlist.toggle(classname)

// 事例 移除 p 具有类`special`的 special 类
toggleclass(document.queryselector('p.special'), 'special')

4.如何获取当前页面的滚动位置?

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}

5.如何平滑滚动到页面顶部?

 const scrolltotop = () => {
     const c = document.documentelement.scrolltop || document.body.scrolltop;
 if (c > 0) {
  window.requestanimationframe(scrolltotop);
  window.scrollto(0, c - c / 8);
 }
}

// 事例
scrolltotop()

window.requestanimationframe()  告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行。

requestanimationframe:优势:由系统决定回调函数的执行时机。60hz的刷新频率,那么每次刷新的间隔中会执行一次回调函数,不会引起丢帧,不会卡顿。

6如何检查父元素是否包含子元素 ?

const elementcontains = (parent, child) => parent !== child && parent.contains(child);

// 事例
elementcontains(document.queryselector('head'), document.queryselector('title')); 
// true
elementcontains(document.queryselector('body'), document.queryselector('body')); 
// false

7.如何检查指定的元素在视口中是否可见 ?

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); // 需要全屏(上下左右)可以见

8.如何获取元素中的所有图像 ?

 const getimages = (el, includeduplicates = false) => {
 const images = [...el.getelementsbytagname('img')].map(img => img.getattribute('src'));
 return includeduplicates ? images : [...new set(images)];
};

// 事例:includeduplicates 为 true 表示需要排除重复元素
getimages(document, true); // ['image1.jpg', 'image2.png', 'image1.png', '...']
getimages(document, false); // ['image1.jpg', 'image2.png', '...']

9. 如何确定设备是移动设备还是台式机/笔记本电脑 ?

 const detectdevicetype = () =>
 /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.useragent)
  ? 'mobile'
  : 'desktop';

// 事例
detectdevicetype(); // "mobile" or "desktop"

10.how to get the current url ?

 const currenturl = () => window.location.href

// 事例
currenturl() // 'https://google.com'

11.如何创建一个包含当前url参数的对象 ?

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

// 事例
geturlparameters('http://url.com/page?n=adam&s=smith'); // {n: 'adam', s: 'smith'}
geturlparameters('google.com'); // {}

12.如何将一组表单子元素转化为对象 ?

 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' }

13.如何从对象检索给定选择器指示的一组属性 ?

 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' }] };

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

14.如何在等待指定时间后调用提供的函数 ? 

const delay = (fn, wait, ...args) => settimeout(fn, wait, ...args);
delay(
 function(text) {
  console.log(text);
 },
 1000,
 'later'
); 

// 1秒后打印 'later'

15.如何在给定元素上触发特定事件且能选择地传递自定义数据 ?

const triggerevent = (el, eventtype, detail) =>
 el.dispatchevent(new customevent(eventtype, { detail }));

// 事例
triggerevent(document.getelementbyid('myid'), 'click');
triggerevent(document.getelementbyid('myid'), 'click', { username: 'bob' });

自定义事件的函数有 event、custoevent 和 dispatchevent;

// 向 window 派发一个resize内置事件
window.dispatchevent(new event('resize'))


// 直接自定义事件,使用 event 构造函数:
var event = new event('build');
var elem = document.queryselector('#id')
// 监听事件
elem.addeventlistener('build', function (e) { ... }, false);
// 触发事件.
elem.dispatchevent(event);

customevent 可以创建一个更高度自定义事件,还可以附带一些数据,具体用法如下:

var myevent = new customevent(eventname, options);
其中 options 可以是:
{
 detail: {
  ...
 },
 bubbles: true,  //是否冒泡
 cancelable: false //是否取消默认事件
}

其中 detail 可以存放一些初始化的信息,可以在触发的时候调用。其他属性就是定义该事件是否具有冒泡等等功能。

内置的事件会由浏览器根据某些操作进行触发,自定义的事件就需要人工触发。 dispatchevent 函数就是用来触发某个事件:

element.dispatchevent(customevent);
上面代码表示,在 element 上面触发 customevent 这个事件。
  // add an appropriate event listener
obj.addeventlistener("cat", function(e) { process(e.detail) });
 
// create and dispatch the event
var event = new customevent("cat", {"detail":{"hazcheeseburger":true}});
obj.dispatchevent(event);

使用自定义事件需要注意兼容性问题,而使用 jquery 就简单多了:

// 绑定自定义事件
$(element).on('mycustomevent', function(){});
 
// 触发事件
$(element).trigger('mycustomevent');
// 此外,你还可以在触发自定义事件时传递更多参数信息:
 
$( "p" ).on( "mycustomevent", function( event, myname ) {
 $( this ).text( myname + ", hi there!" );
});
$( "button" ).click(function () {
 $( "p" ).trigger( "mycustomevent", [ "john" ] );
});

16.如何从元素中移除事件监听器 ?

const off = (el, evt, fn, opts = false) => el.removeeventlistener(evt, fn, opts);

const fn = () => console.log('!');
document.body.addeventlistener('click', fn);
off(document.body, 'click', fn); 

17.如何获得给定毫秒数的可读格式 ?

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'

18.如何获得两个日期之间的差异 (以天为单位) ?

const getdaysdiffbetweendates = (dateinitial, datefinal) =>
 (datefinal - dateinitial) / (1000 * 3600 * 24);

// 事例
getdaysdiffbetweendates(new date('2017-12-13'), new date('2017-12-22')); // 9

19.如何向传递的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
); 

// {"userid": 1, "id": 1, "title": "sample title", "body": "my text"}

20. 如何对传递的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
); 

// {"userid": 1, "id": 1337, "title": "foo", "body": "bar bar bar"}

21.如何为指定选择器创建具有指定范围,步长和持续时间的计数器 ?

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”`的元素创建一个2秒计时器

22.如何将字符串复制到剪贴板 ?

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

23.如何确定页面的浏览器选项卡是否聚焦 ?

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

// 事例
isbrowsertabfocused(); // true

24. 如何创建目录 (如果不存在) ?

const fs = require('fs');
const createdirifnotexists = dir => (!fs.existssync(dir) ? fs.mkdirsync(dir) : undefined);

// 事例
createdirifnotexists('test'); 

这里面的方法都挺实用的,可以解决很多开发过程问题,大家就好好利用起来吧 !

到此这篇关于24个es6方法解决js实际开发问题的文章就介绍到这了,更多相关es6方法解决实际开发内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网