将一个html元素渲染到浏览器视口

时间:2015-03-04 00:12:31

标签: javascript jquery html css dom

这可能超出了本网站的范围,但我试图弄清楚这个页面:http://www.borngroup.com/如何能够渲染大猩猩动画,它将宽度/高度div扩展到浏览器视口;之后,您可以向下滚动并查看其余页面内容。

我一直在尝试使用jQuery来获取浏览器视口的高度和宽度,然后相应地设置CSS元素的宽度/高度属性;这有点像一个悲惨的失败。然后,我想到了使用css在DOM中渲染单个元素隐藏其余元素,然后使用JavaScript检测鼠标向下滚动,然后使网站的其余部分可见。但是,这并没有奏效。 ):

1 个答案:

答案 0 :(得分:0)

为您写的代码。完全响应,调整宽度/高度,可以设置最小值。它基于window width to video widthwindow height to video height比率。 自动定心垂直和水平工作。

JSFiddle

<强> JS:

$(document).ready(function (){

    $(window).on('resize', function (){

        var windowWidth = $(window).innerWidth();
        var windowHeight = $(window).innerHeight();
        var videoWidth = $('#video-container video').outerWidth();
        var videoHeight = $('#video-container video').outerHeight();
        var widthRatio = windowWidth/videoWidth;
        var heightRatio = windowHeight/videoHeight;

        if((widthRatio > heightRatio) || (widthRatio == heightRatio)){

            $('#video-container video').css({

                'width':    windowWidth,
                'height':   'auto'
            });
        }
        else{

            $('#video-container video').css({

                'width':    'auto',
                'height':   windowHeight
            });
        }

        var newVideoWidth = $('#video-container video').outerWidth();
        var newVideoHeight = $('#video-container video').outerHeight();

        $('#video-container video').css({

            'left':     '0px',
            'top':      '0px'
        });

        if(newVideoWidth > windowWidth){

            $('#video-container video').css('left', ((windowWidth-newVideoWidth)/2)+'px');
        }

        if(newVideoHeight > windowHeight){

            $('#video-container video').css('top', ((windowHeight-newVideoHeight)/2)+'px');
        }
    }).trigger('resize');
});
相关问题