H5自定义标签Video播放器

Web Components才是组件化的未来

上一时代的牺牲品是jQuery,如今Web Components被越来越多的浏览器所支持,React,Vue或许是下一个“祭品”。

组件化、复用,这几乎是所有开发者追求的东西。Web Components就是为此而提出。可以使用来创建封装功能的定制元素,可以在你喜欢的任何地方重用,不必担心代码冲突。

这样的理念和Vue十分相似,专注于组件。所以Web Components或许是未来的方向!

组件是 Web 开发的方向,现在的热点是 JavaScript 组件,但是 HTML 组件未来可能更有希望。

浏览器将自定义元素保留在 DOM 之中,但不会任何语义。除此之外,自定义元素与标准元素都一致

事实上,浏览器提供了一个HTMLUnknownElementHTMLElement对象,所有自定义元素都是该对象的实例。

1
2
3
var tabs=document.createElement("tabs");
console.log(tabs instanceof HTMLUnknownElement); //true
console.log(tabs instanceof HTMLElement); //true

Custom Elements 标准: 自定义元素的名字必须包含一个破折号(-)
一旦名字之中使用了破折号,自定义元素就不是HTMLUnknownElement的实例了。

1
2
3
var tabs=document.createElement("my-tabs");
console.log(tabs instanceof HTMLUnknownElement); //false
console.log(tabs instanceof HTMLElement); //true

Custom Elements 标准规定了,自定义元素的定义可以使用 ES6 的class语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
<my-element content="Custom Element">
Hello
</my-element>
</body>
</html>
<script>

class MyElement extends HTMLElement {//自定义元素的定义可以使用ES6的class语法
get content() {
return this.getAttribute('content');
}

set content(val) {
this.setAttribute('content', val);
}
}
// 原生的window.customElements对象的define方法用来定义 Custom Element。
// 该方法接受两个参数,第一个参数是自定义元素的名字,第二个参数是一个 ES6 的class。
window.customElements.define('my-element', MyElement);

window.onload=function(){//在页面元素加载完之后,才执行
function customTag(tagName, fn){//Array.from([arguments]);可以将字符串,数组,类数组集合转化为数组
Array
.from(document.getElementsByTagName(tagName))
.forEach(fn);
}
function myElementHandler(element) {
element.textContent = element.content;
}
customTag('my-element', myElementHandler);
};
</script>

自定义elements

Web Components通过CustomElementRegistry.define()来定义elements,目前有两种elements,独立的element与继承自基本的HTML element

独立的element

独立的element像这样的自定义标签

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
customElements.define('custom-element',
class MyCustomElement extends HTMLElement {
constructor() {
super();

//创建<p stype='color:red'></p>
const pElem = document.createElement('p');
pElem.textContent = this.textContent;
pElem.style.color = 'red';
//加入根节点
const shadowRoot = this.attachShadow({mode: 'closed'});
shadowRoot.appendChild(pElem);

}
}
)


...

<custom-element>红色字体的段落!</custom-element>

生命周期回调函数

在自定义的element的构造函数中,可以指定多个不同的回调函数,它们将会在元素的不同生命时期被调用:

  • connectedCallback:当 custom element首次被插入文档DOM时,被调用。
  • disconnectedCallback:当 custom element从文档DOM中删除时,被调用。
  • adoptedCallback:当 custom element被移动到新的文档时,被调用。
  • attributeChangedCallback: 当 custom element增加、删除、修改自身属性时,被调用。
    例如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
customElements.define('other-custom-element',
class MyOtherCustomElement extends HTMLElement {
constructor() {
super();
//......
}
connectedCallback() {
console.log('Custom square element added to page.');
}
disconnectedCallback() {
console.log('Custom square element removed from page.');
}
adoptedCallback() {
console.log('Custom square element moved to new page.');
}
attributeChangedCallback(name, oldValue, newValue) {
console.log('Custom square element attributes changed.');
}
}
)

Shadow DOM

image

如图,Shadow DOM会在自定义标签解析时,加载到普通的DOM上。内部可以通过Element.attachShadow()来获取shadow root。它有一个mode属性,值可以是open或者closed,表示能否在外部获取Shadow DOM对象,一般而言应当为closed,内部实现不应该对外可见。

HTML templates

如果你熟悉Vue的话,这块与它很相似,是template与slot。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<template id="person-template">
<div>
<h2>Personal ID Card</h2>
<slot name="person-name">NAME MISSING</slot>
<ul>
<li><slot name="person-age">AGE MISSING</slot></li>
<li><slot name="person-occupation">OCCUPATION MISSING</slot></li>
</ul>
</div>
</template>
<person-details>
<!-- 官方例子p slot="person-name",由于hexo对p的解析会出错,这里改成了<span> -->
<span slot="person-name">Morgan Stanley</span>
<span slot="person-age">36</span>
<span slot="person-occupation">Accountant</span>
</person-details>

1
2
3
4
5
6
7
8
9
10
customElements.define('person-details',
class extends HTMLElement {
constructor() {
super();
const template = document.getElementById('person-template');
const templateContent = template.content;
const shadowRoot = this.attachShadow({mode: 'closed'});
shadowRoot.appendChild(templateContent.cloneNode(true));
}
});

HTML Imports

这块存在争议,Mozilla认为将来应该用更合适的方式。不多做介绍。

Web Components视频播放器

参考项目:https://github.com/yisar/eplayer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
class Eplayer extends HTMLElement {
constructor () {
super()
this.doms = {}
this.src = this.getAttribute('src')
this.type = this.getAttribute('type')

this.init()
this.stream()
}

static get observedAttributes () {
return ['src', 'type']
}

attributeChangedCallback (name, _, newVal) {
if (name === 'src') this.src = this.$('.video').src = newVal
if (name === 'type') this.type = newVal
this.stream()
this.video.load()
}

$ (key) {
return this.doms[key]
}

waiting () {
this.$('.mark').classList.remove('playing')
this.$('.mark').classList.add('loading')
}

stream () {
switch (this.type) {
case 'hls':
if (Hls.isSupported()) {
let hls = new Hls()
hls.loadSource(this.src)
hls.attachMedia(this.video)
}
break
}
}

canplay () {
this.$('.mark').classList.remove('loading')
this.$('.mark').classList.add('playing')
this.$('.mark').onclick = () => {
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.play()
}, 200)
}
this.$('.total').innerHTML = getTimeStr(this.video.duration)
}

play () {
if (this.video.paused) {
this.video.play()
this.$('.ep-video').style.display = 'none'
this.$('.is-play').classList.replace('ep-play', 'ep-pause')
} else {
this.video.pause()
this.$('.ep-video').style.display = 'block'
this.$('.is-play').classList.replace('ep-pause', 'ep-play')
}
}

volume () {
if (this.video.muted) {
this.video.muted = false
setVolume(this.video.volume * 10, this.$('.line'))
this.$('.is-volume').classList.replace('ep-volume-off', 'ep-volume')
} else {
this.video.muted = true
setVolume(0, this.$('.line'))
this.$('.is-volume').classList.replace('ep-volume', 'ep-volume-off')
}
}

update () {
let cTime = getTimeStr(this.video.currentTime)
if (this.video.buffered.length) {
let bufferEnd = this.video.buffered.end(this.video.buffered.length - 1)
this.$('.buffer').style.width =
(bufferEnd / this.video.duration) * this.$('.progress').clientWidth +
'px'
}
let offset =
(this.video.currentTime / this.video.duration) * this.$('.bg').clientWidth
this.$('.now').innerHTML = cTime
this.$('.current').style.width = offset + 'px'
}

progress (e) {
let offset = e.offsetX / this.$('.progress').offsetWidth
this.video.currentTime = this.video.duration * offset
}

down (e) {
e.stopPropagation()
this.disX = e.clientX - this.$('.cycle').offsetLeft
document.onmousemove = e => this.move(e)
document.onmouseup = () => {
e.stopPropagation()
document.onmousemove = null
document.onmouseup = null
}
}

move (e) {
e.stopPropagation()
let offset = e.clientX - this.disX + 7
if (offset < 0) offset = 0
if (offset > this.$('.progress').clientWidth) {
offset = this.$('.progress').clientWidth
}
this.$('.current').style.width = offset + 'px'
this.video.currentTime =
(offset / this.$('.progress').clientWidth) * this.video.duration
document.onmousemove = null
setTimeout(
(document.onmousemove = e => {
if (e) this.move(e)
}),
30
)
}

alow () {
clearTimeout(this.timer)
this.$('.controls').style.bottom = 0
this.$('.ep-video').style.bottom = 70 + 'px'
this.$('.mark').style.cursor = 'default'
this.timer = setTimeout(() => {
this.$('.controls').style.bottom = -70 + 'px'
this.$('.ep-video').style.bottom = 25 + 'px'
this.$('.mark').style.cursor = 'none'
}, 5000)
}

keydown (e) {
switch (e.keyCode) {
case 37:
this.video.currentTime -= 10
break
case 39:
this.video.currentTime += 10
break
case 38:
try {
this.video.volume = parseInt(this.video.volume * 100) / 100 + 0.05
} catch (e) {}
setVolume(this.video.volume.toFixed(1) * 10, this.$('.line'))
break
case 40:
try {
this.video.volume = parseInt(this.video.volume * 100) / 100 - 0.05
} catch (e) {}
setVolume(this.video.volume.toFixed(1) * 10, this.$('.line'))
break
case 32:
this.play()
break
default:
}
}

ended () {
this.$('.is-play').classList.replace('ep-pause', 'ep-play')
}

full () {
if (isFullScreen()) {
if (document.exitFullscreen) {
document.exitFullscreen()
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen()
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen()
} else if (document.msExitFullscreen) {
document.msExitFullscreen()
}
} else {
let el = this.$('.eplayer')
let rfs =
el.requestFullScreen ||
el.webkitRequestFullScreen ||
el.mozRequestFullScreen ||
el.msRequestFullscreen
return rfs.call(el)
}
}

panel (e) {
e.preventDefault()
let panel = this.$('.panel')
if (e.button !== 2) {
panel.style.display = 'none'
} else {
panel.style.display = 'block'
panel.style.height = panel.childElementCount * 24 + 'px'
panel.style.top = e.offsetY + 'px'
panel.style.left = e.offsetX + 'px'
}
}

init () {
let html = `
<style>
@import "https://at.alicdn.com/t/font_836948_6lbb2iu59.css";
*{
padding:0;
margin:0;
}
li{
list-style:none;
}
.eplayer,video{
height:100%;
width:100%;
color:var(--icons,rgba(255,255,255,0.6));
font-size:12px;
background:#000
}
.eplayer{
user-select:none;
position: relative;
overflow: hidden;
}
.controls{
position:absolute;
left:0;
right:0;
bottom:0;
padding:10px;
background:linear-gradient(transparent,rgba(0,0,0,.5));
transition: .3s ease-out;
z-index:1;
}
.progress{
position:relative;
bottom:15px;
left:0;
right:0;
cursor:pointer;
}
.options{
display:flex;
align-items:center;
}
.epicon{
color:var(--icons,rgba(255,255,255,0.6));
padding:0 10px;
}
.epicon{
font-size:18px;
transition: .3s;
cursor:pointer;
}
.epicon:hover{
color:#fff;
}
.time{
position:relative;
top:-2px;
}
.time b{
font-weight:normal;
}
.line{
padding:0 1px;
margin-bottom: -2px;
cursor:pointer
}
.line i{
width:4px;
border-radius:4px;
display: inline-block;
background: var(--icons,rgba(255,255,255,0.6));
height: 12px;
transform:scaleX(0.7);
transition: .3s;
}
.line:hover i{
height:14px;
background:var(--theme,#c136e4);
}
.active i{
background:var(--theme,#c136e4);
}
.left{
flex:1;
}
.right{
flex:1;
display:flex;
align-items:center;
justify-content: flex-end;
}
.bg,.current,.buffer{
left:0;
height:3px;
position:absolute;
top:0;
}
.bg{
right:0;
background:var(--progress,rgba(255,255,255,.3));
}
.current{
background:var(--theme,#c136e4);
}
.buffer{
background:var(--buffer,rgba(255,255,255,.5));
}
.dot{
position:absolute;
border-radius: 50%;
display: block;
background:var(--theme,#c136e4);
height: 9px;
width:9px;
right:-5px;
top:-3px;
cursor:pointer;
z-index:1;
}
.cycle{
position:absolute;
border-radius: 50%;
display: block;
background:var(--theme,#c136e4);
opacity:0.3;
height: 15px;
width:15px;
right:-8px;
top:-6px;
cursor:pointer;
z-index:1;
}
@keyframes loading{
0%{
transform: rotate(0deg);
}
100%{
transform: rotate(360deg);
}
}
.playing{
position: absolute;
z-index: 1;
top:0;
left:0;
right:0;
bottom:0;
}
.loading {
position: absolute;
z-index: 1;
top: 50%;
left: 50%;
margin:-20px 0 0 -20px;
width: 40px;
height: 40px;
z-index:1;
box-shadow: 2px 0px rgba(255,255,255,.6);
border-radius: 50%;
animation: loading 1s linear infinite;
}
.ep-video {
position: absolute;
bottom: 25px;
right: 20px;
font-size:40px;
color:var(--icons,rgba(255,255,255,.6));
z-index:1;
cursor: pointer;
}
.panel {
position: absolute;
bottom: 200px;
right: 300px;
background:rgba(0,0,0,.8);
border-radius:4px;
cursor: pointer;
z-index: 1;
display:none;
width:150px;
}
.panel li{
line-height:24px;
text-align:center;
}
.panel li:hover{
border-radius:4px;
background:rgba(0,0,0,.8)
}
</style>
<div class="eplayer">
<video id="video" class="video" src="${this.src || ''}"></video>
<div class="mark loading"></div>
<div class="controls" style="bottom:-50px">
<div class="progress">
<b class="bg"></b>
<b class="buffer"></b>
<div class="current" style="width:0">
<div class="dot"></div>
<div class="cycle"></div>
</div>
</div>
<div class="options">
<div class="left">
<i class="epicon ep-play is-play"></i>
<span class="time">
<b class="now">00:00</b> / <b class="total">00:00</b>
</span>
</div>
<div class="right">
<i class="epicon ep-volume is-volume"></i>
<span class="line"><i></i></span>
<span class="line"><i></i></span>
<span class="line"><i></i></span>
<span class="line"><i></i></span>
<span class="line"><i></i></span>
<span class="line"><i></i></span>
<span class="line"><i></i></span>
<span class="line"><i></i></span>
<span class="line"><i></i></span>
<span class="line"><i></i></span>
<i class="epicon ep-full"></i>
</div>
</div>
</div>
<div class="epicon ep-video"></div>
<div class="panel"></div>
</div>
`
let template = document.createElement('template')
template.innerHTML = html
this.attachShadow({
mode: 'open'
}).appendChild(template.content.cloneNode(true))

const doms = [
'.video',
'.mark',
'.playing',
'.loading',
'.total',
'.now',
'.current',
'.buffer',
'.is-play',
'.ep-video',
'.is-volume',
'.cycle',
'.progress',
'.controls',
'.line',
'.ep-pause',
'.ep-play',
'.ep-volume-off',
'.ep-volume',
'.bg',
'.eplayer',
'.ep-full',
'.panel'
]

for (const key of doms) {
let dom = this.shadowRoot.querySelectorAll(key)
this.doms[key] = dom.length > 1 ? [...dom] : dom[0]
}
this.mount()

for (const name in Eplayer.plugins) {
const cb = Eplayer.plugins[name]
let node = document.createElement('li')
node.innerText = name
let panel = this.$('.panel')
panel.appendChild(node)
node.addEventListener('click', () => cb(this.shadowRoot))
}
}

mount () {
this.video = this.$('.video')
this.video.volume = 0.5
setVolume(this.video.volume * 10, this.$('.line'))
this.$('.is-volume').onclick = () => this.volume()
this.$('.line').forEach((item, index) => {
item.onclick = () => {
this.video.volume = (index + 1) / 10
setVolume(index + 1, this.$('.line'))
}
})
this.$('.progress').onmousedown = e => this.progress(e)
this.video.onwaiting = () => this.waiting()
this.video.oncanplay = () => this.canplay()
this.video.ontimeupdate = () => this.update()
this.$('.cycle').onmousedown = e => this.down(e)

this.$('.eplayer').onmousemove = () => this.alow()
document.onkeydown = e => this.keydown(e)
this.$('.ep-full').onclick = () => this.full()
this.$('.ep-video').onclick = this.$('.is-play').onclick = () => this.play()
this.video.onended = () => this.ended()
this.$('.mark').ondblclick = () => {
clearTimeout(this.timer)
this.full()
}
this.$('.eplayer').oncontextmenu = e => false
this.$('.mark').onmousedown = e => this.panel(e)
}
}

Eplayer.plugins = {}

Eplayer.use = function (name, cb) {
this.plugins[name] = cb
}


function getTimeStr (time) {
let h = Math.floor(time / 3600)
let m = Math.floor((time % 3600) / 60)
let s = Math.floor(time % 60)
h = h >= 10 ? h : '0' + h
m = m >= 10 ? m : '0' + m
s = s >= 10 ? s : '0' + s
return h === '00' ? m + ':' + s : h + ':' + m + ':' + s
}

function setVolume (index, node) {
for (let j = index; j < node.length; j++) {
node[j].classList.remove('active')
}
for (let i = 0; i < index; i++) {
node[i].classList.add('active')
}
}

function isFullScreen () {
return (
document.isFullScreen ||
document.webkitIsFullScreen ||
document.mozIsFullScreen
)
}

;(function () {
let link = document.createElement('link')
link.setAttribute('href', 'https://at.alicdn.com/t/font_836948_6lbb2iu59.css')
link.setAttribute('rel', 'stylesheet')
document.head.appendChild(link)
})()

Eplayer.use(
'github源码',
ep => {
window.location.href = 'https://github.com/132yse/eplayer'
}
)

customElements.define('e-player', Eplayer)

image

HTML 自定义元素教程

Web Components 入门实例教程

Web Components实践