昨天改了一个H5播放器的皮肤,新学到了移除组件、新增组件、Control布局配置的方法。趁着还记得赶紧记录下。
对于Component的具体用法可以看videoJs的官方文档:传送门
videoJs默认皮肤时有一个很丑的左上角居中的播放按钮,以往的操作都是使用display:none隐藏该元素或者用flex|绝对定位来居中它。
![]()
这次读了Component之后学到一个新技能来隐藏它:
| 12
 3
 4
 5
 6
 7
 8
 
 | function init () {
 this.player = videoJS(element, options, function () {
 console.log('onReady')
 })
 
 this.player.removeChild('BigPlayButton')
 }
 
 | 
新增组件
这里参考微博的H5播放器,它自定义了左上角的关闭按钮:
![]()
那我们如何来添加这个按钮呢,过去的做法是手动创建一个div然后css绝对定位,就像这样:
| 1
 | <button style="position: absolute;left: 10px;right: 10px" onclick="onClickEvent()">X</button>
 | 
现在学会了创建组件之后,可以用下面的方式来添加组件:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 
 | function create () {const Button = videoJS.getComponent('Button')
 const btnClose = new Button(this.player)
 
 btnClose.addClass('btn-close')
 
 btnClose.removeClass('vjs-control')
 btnClose.removeClass('vjs-button')
 
 btnClose.on('click', function () {
 console.log('click')
 })
 
 this.player.addChild(btnClose)
 }
 
 | 
总结:
- 通过addClass和removeClass来增减css样式
- 使用on来绑定事件,移动端点击使用tap,PC端使用click
- 最后需要通过videoJsElement.addChild(component)的方式来把组件添加到播放器上
Control布局配置
我在翻阅官方文档的过程中,发现可以通过修改controlBar来操作controls子组件的显示和排序。例子如下:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 
 | videoJs(xxx, {controls: true,
 controlBar: {
 children: [
 { name: 'playToggle' },
 { name: 'volumePanel', inline: false },
 { name: 'currentTimeDisplay' },
 { name: 'TimeDivider' },
 { name: 'progressControl' },
 { name: 'durationDisplay' }
 ]
 }
 })
 
 | 
修改完之后的效果图:
![]()
所有的默认组件名称看这里:传送门