-1

如何使图像适合屏幕(不是完整的背景图像),以便在向下滚动时显示其他内容?

我正在谈论的一个例子在这里:

http://www.microsoft.com/visualstudio/eng/products/visual-studio-professional-2012

在该示例中,查看图像在调整屏幕大小并向下滚动时的反应。

我期待着您的回复。

谢谢你。

PS:如果您也可以发送它的演示,那将非常有帮助。谢谢!

4

1 回答 1

0

以下 JS 应该会有所帮助:

    function resizeBackground() 
{
    var targetWidth;
    var targetHeight;

    if (typeof window.innerWidth != 'undefined')
    {
        targetWidth = window.innerWidth,
        targetHeight = window.innerHeight
    }
    else if (typeof document.documentElement != 'undefined'&& typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
    {
        targetWidth = document.documentElement.clientWidth,
        targetHeight = document.documentElement.clientHeight
    }
    else
    {
        targetWidth = document.getElementsByTagName('body')[0].clientWidth,
        targetHeight = document.getElementsByTagName('body')[0].clientHeight
    }

    var background = new Image();
    background.src = document.getElementById("backgroundImage").src;
    var target = document.getElementById("backgroundImage");
    var sourceWidth = background.width;
    var sourceHeight = background.height;

    if (targetWidth / sourceWidth > targetHeight / sourceHeight)
    {
        target.width = targetWidth;
        target.height = sourceHeight * (targetWidth / sourceWidth);
    }
    else
    {
        target.width = sourceWidth * (targetHeight / sourceHeight);
        target.height = targetHeight;
    }
}
window.onload = resizeBackground;
window.onresize = resizeBackground;

然后将 div 插入到您想要图像的任何位置:

<div id= 'backgroundimage'></div>

最后是 CSS:

#backgroundimage {background-image:url(image.jpg); width:100%;}
于 2013-07-19T01:13:16.693 回答