如何根据当前页面高度调整具有渐变的图像的大小

How to resize an image that has a gradient according to the current page height?

本文关键字:渐变 图像 调整 何根 当前页 高度      更新时间:2023-09-26

我正在使用图像作为我网站的背景。它具有黑/白渐变,宽度为1px。

CSS:

background-image:url('../image/gradient.png');

这使它重演。图像的高度为 2000 像素。

是否可以动态更改图像的高度,使其适合所有页面大小:如果页面高度小于2000px,则图像的高度应较小,如果页面高度较大,则图像应更大。

提前致谢

我尝试了各种浏览器内渐变技术,它们似乎在所有浏览器上的工作方式都不一样。

我通常以两种方式之一来解决这个问题。

如果你可以使用CSS3,那么使用CSS渐变(我总是发现 http://colorzilla.com/gradient-editor/玩渐变的不错选择),然后你可以将其设置为窗口的100%高度。

如果 CSS3 不是一个选项,我通常只选择一个高度,比如 500px,并为此制作一个渐变。然后,由于渐变通常从颜色 A 变为颜色 B,因此只需设置底层背景颜色以匹配颜色 B,渐变将在所有显示器上类似地工作。

假设从蓝色到黑色的渐变:

body {
    /* ensure body always fills viewport */
    min-height: 100%;
    /*gradient fades to black so set underlying BG to black*/
    background: url(/path/to/gradient.gif) repeat-x #000; 
}
}

也许我没有得到您问题的正确上下文,但这可以通过诸如

#SomeImg.src {
width: 100%;
position: absolute;
top: 0;
left: 0;
}

调整此页面大小以查看其操作:http://css-tricks.com/examples/ImageToBackgroundImage/

使用 CSS3,您可以使用background-size: cover这里讨论一些其他技术。

您可以创建多个具有不同高度的图像,并动态匹配最接近的图像大小。如果执行此操作,则需要绑定到 window.resize 事件以在用户调整窗口大小时更新图像。

window.onload = setBackgroundImage;
window.onresize = setBackgroundImage;
function setBackgroundImage() {
    var winH = 500;
    if (document.body && document.body.offsetWidth) {
        winH = document.body.offsetHeight;
    } else if (document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetWidth ) {
        winH = document.documentElement.offsetHeight;
    } else if (window.innerWidth && window.innerHeight) {
        winH = window.innerHeight;
    }
    if (winH > 400) {
        document.body.style.backgroundImage = "url('../image/gradient800px.png')";
    } else if (winH > 800) {
        document.body.style.backgroundImage = "url('../image/gradient1000px.png')";
    } else if (winH > 1000) {
        document.body.style.backgroundImage = "url('../image/gradient1500px.png')";
    } else if (winH > 1500) {
        document.body.style.backgroundImage = "url('../image/gradient2000px.png')";
    } else {
        document.body.style.backgroundImage = "url('../image/gradient400px.png')";
    }
}

我不认为解决方案很漂亮,但它应该有效。