html5的video的封面poster圖片填充

html5支持視頻播放,並且趨勢,facebook也全面切換到html5了,最近作一個簡單的視頻播放器,測試了好多jplayer,video.js之類的都以爲不太好,因此本身寫一個最簡單的,不過發現了一個問題,視頻播放以前的封面不太好……css

封面的尺寸被強制縮小了,我須要填充整個播放器的。html

< !DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8"/>
        <title></title>
        <style type="text/css">
        .video-container1{
            width: 400px;
            height: 400px;
            border: solid;
        }
        .video1{
            width: 100%;
            height: 100%;
        }
        </style>
    </head>
    <body>
    <div class="video-container1">
        <video class="video1" src="oceans.mp4" poster="1.jpg" controls>

        </video>
    </div>
    </body>
</html>

blog_html5_video_background_01_20151223.jpg
blog_html5_video_background_02_20151223.jpg

因此查了一下資料,並無發現html5的video屬性支持處理poster的尺寸問題,而後發現了一個hacker的方法:
The answer is actually quite simple. Instead of providing our poster image as a value to the poster attribute, we define it as a background image for our video element, and use the background-size property to tell the browser that the image is to cover the element in question:html5

將poster頁面設置爲一個透明的圖片或者不存在的值,這樣瀏覽器就會沒法顯示poster,而後經過設置播放器的css背景background,將咱們須要的背景圖放進去,而且填充背景,而且咱們用background-size屬性去告訴瀏覽器,這個播放器或者這個元素被這個圖片覆蓋。git

video{
    width: 100%;
    height: 100%;
    background:transparent url('img/1.jpg') 50% 50% no-repeat;

    //下面就是background-size,每種瀏覽器都寫一個配置
    -webkit-background-size:cover;
    -moz-background-size:cover;
    -o-background-size:cover;
    background-size:cover;
}

詳細代碼在這裏:
友人提醒,將測試代碼放到github方便其餘人測試:(https://github.com/yuanyuanyuan/my-git/tree/master/test1github

< !DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8"/>
        <title></title>
        <style type="text/css">
        .video-container1{
            width: 400px;
            height: 400px;
            border: solid;
        }
        .video1{
            width: 100%;
            height: 100%;
        }
        .video-container2{
            width: 400px;
            height: 400px;
            border: solid;
        }
        .video2{
            width: 100%;
            height: 100%;
            background:transparent url('1.jpg') 50% 50% no-repeat;
            -webkit-background-size:cover;
            -moz-background-size:cover;
            -o-background-size:cover;
            background-size:cover;
        }
        </style>
    </head>
    <body>
    <div class="video-container1">
        <video class="video1" src="oceans.mp4" poster="1.jpg" controls>

        </video>
    </div>
    <div class="video-container2">
        <video class="video2" src="oceans.mp4" poster="2.jpg" controls>

        </video>
    </div>
    </body>
</html>

展現效果以下:web

blog_html5_video_background_03_20151223.jpg

引用參考:
http://www.iandevlin.com/blog/2013/03/html5/html5-video-and-background-images
http://www.w3school.com.cn/cssref/pr_background.asp
http://www.w3schools.com/css/css_image_transparency.asp瀏覽器

相關文章
相關標籤/搜索