1. 程式人生 > >動態設定video的寬高的方法,js設定和CSS設定

動態設定video的寬高的方法,js設定和CSS設定

一、csss設定

html:

<div class="wrap">
    <video controls="controls"  class="videoBox" #iframeurl>
        <source src="3a1be272f8b.mp4" type="video/mp4" />
    </video>
</div>
css:
.wrap{
    width:100%;
position:relative;
padding-bottom:62%;    /*需要用padding來維持16:9比例,也就是9除以16*/
height: 0; video{ position: absolute; top:0; left: 0; width: 100%; height: 100% } }
JS的方法:

思路:用js獲取到當前video的DOM,再對DOM進行動態的寬高設定

以下是以angular的例子展示,在純JS裡面也是一樣的道理

html:

<video controls="controls"  class="videoBox" #iframeurl>
    <source src="a1be272f8b.mp4" type="video/mp4" />
</video>
TS:

獲取DOM的方法

@ViewChild('iframeurl') iframeurl:ElementRef;
let iwidth = screen.width;
let iheight = iwidth*0.62;
console.log(iheight+"高度"+iwidth);
this.iframeurl.nativeElement.style.width = iwidth+"px";
this.iframeurl.nativeElement.style.height = iheight+"px";