Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

javascript - Make a div's size and position the same as a video's

I have an HTML5 video with a width of 100% and also a height of 100% , and I want to wrap a div to fit the size and position of the video (not the video tag, but the video itself) using anything necesary.

[See Fiddle]

HTML:

<div id="wrapper"></div>
<video id="vid" controls preload="none" width="100%" height="100%" poster="http://video-js.zencoder.com/oceans-clip.png">
    <source src="http://video-js.zencoder.com/oceans-clip.mp4" type='video/mp4'/>
    <source src="http://video-js.zencoder.com/oceans-clip.webm" type='video/webm'/>
    <source src="http://video-js.zencoder.com/oceans-clip.ogv" type='video/ogg'/>
</video>

CSS:

#wrapper{
  width: 2px;
  height: 2px;
  border: solid 2px red;
  position: absolute;
}

JS (jQuery):

setInterval(function(){
    $("#vid").height($(window).height() - $("header").height() - 7);
    /*There is a header and a bunch of other stuff in the original code*/
}, 10);

This is my first question here so if you need anything I'll be glad to answer. Thanks.

EDIT: What I need is something like this

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Calculation of the height and width of the video using the video's aspect ratio seems necessary. Your fiddle puts a height on the video element (set to 264), which is not the same as your question's code sample. Which is more appropriate to your question?

That being said, perhaps something like this can attempt to calculate the proper height and the top css value of the wrapper, assuming the video width will be landscape (full window width):

JAVASCRIPT:

var vidRatio = $("#vid").height()/$("#vid").width();

setInterval(function(){
    $("#vid").height($(window).height() - $("header").height() - 7);
    var width = $(window).width()-20; // abitrary 20 pixels to account for border/margin/padding?
    $("#wrapper").css({
        'width': width, 
        'height':width*vidRatio,
        'top':($(window).height()-width*vidRatio)/2
    });
/*There is a header and a bunch of other stuff in the original code*/
}, 10);

CSS:

#wrapper
{
    width: 2px;
    height: 2px;
    border: solid 2px red;
    position:absolute;
}

http://jsfiddle.net/lsubirana/1Ly0f5cx/

It's not perfect but may help.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...