Html 替代背景尺寸:在 IE7+ 中覆盖

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10142491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:46:10  来源:igfitidea点击:

Alternative for background-size:cover in IE7+

htmlinternet-explorercss

提问by ediblecode

I have a background image on the body of my web page. I have used background-size:coverso that the image stretches across the body whilst maintaining the aspect ratio of the image. I would like this to be the same for IE7 + IE8.

我的网页正文中有一个背景图片。我已经使用过background-size:cover使图像在整个身体上伸展,同时保持图像的纵横比。我希望这对于 IE7 + IE8 来说是一样的。

I have looked around and seen the following code:

我环顾四周,看到了以下代码:

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
    src='AutumnWinter_4.jpg',
    sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(
    src='AutumnWinter_4.jpg',
    sizingMethod='scale')";

But this doesn't preserve the aspect ratio, which is really bad for the website we are aiming at.

但这并不能保持纵横比,这对我们瞄准的网站来说真的很糟糕。

Is there any way to do this? Without hitting up jQuery?

有没有办法做到这一点?不打jQuery?

采纳答案by The John Smith

backgroundSize.js will not actually stretch the bg image in IE7, it seems to just center it at the original size. See their demoand click on 'Check what IE6-7-8 users would normally see.'

backgroundSize.js 实际上不会在 IE7 中拉伸 bg 图像,它似乎只是将其以原始大小居中。查看他们的演示并单击“检查 IE6-7-8 用户通常会看到什么”。



@danRhul

@danRhul

I have read that backstretchwill work in IE7+

我读过 backstretch可以在 IE7+ 中使用

Good luck!

祝你好运!

回答by Fabrizio Calderan

What's the reason of not using jQuery? You could load it in conditional comments for IE<8only, so that for every other modern browser jQuery is not loaded.

不使用jQuery的原因是什么?您可以IE<8仅在条件注释中加载它,以便不会加载其他所有现代浏览器的 jQuery。

Also consider that IE7 has a very low market share (2,52%, April 2012)so it can be acceptable to load ~ 25kb extra for that specific browser if this feature is so important for your site/application.

还要考虑到 IE7 的市场份额非常低(2.52%,2012 年 4 月),因此如果此功能对您的站点/应用程序非常重要,那么为该特定浏览器加载约 25kb 的额外空间是可以接受的。

So, I've found this plugin for jQuery: https://github.com/louisremi/jquery.backgroundSize.js

所以,我找到了这个 jQuery 插件:https: //github.com/louisremi/jquery.backgroundSize.js

A jQuery cssHook adding support for "cover" and "contain" to IE6-7-8, in 1.5K

一个 jQuery cssHook,在 1.5K 中为 IE6-7-8 添加了对“cover”和“contain”的支持

See Github project pagefor more info.

有关更多信息,请参阅Github 项目页面

回答by DACrosby

You could just fake a background image with an actual image. It's a bit more HTML editing and certainly not ideal, but since when has handling IE ever been ideal?

您可以使用实际图像来伪造背景图像。它是更多的 HTML 编辑,当然不是理想的,但是从什么时候开始处理 IE 是理想的?

<body>
  <img id="mainBG" src="mainBG.jpg" />
  <div id="content">
  [ ... ]

Then style it accordingly

然后相应地设置样式

body{
  position:relative;
}
#mainBG{
  width:100%
  position:absolute;
  top:0px;
  left:0px;
}

Should be cross-browser if I'm not mistaken.

如果我没记错的话应该是跨浏览器的。

回答by Dean_Wilson

I've used the following (http://css-tricks.com/perfect-full-page-background-image/) and it works well in ie7.

我使用了以下(http://css-tricks.com/perfect-full-page-background-image/)并且它在 ie7 中运行良好。

HTML:

HTML:

<body>
    <img class="bg" src="filename">       
</body>   

CSS:

CSS:

.bg {
    /* Set rules to fill background */
    min-height: 100%;
    min-width: 1024px;

    /* Set up proportionate scaling */
    width: 100%;
    height: auto;

    /* Set up positioning */
    position: fixed;
    top: 0;
    left: 0;
}

@media screen and (max-width: 1024px) { /* Specific to this particular image */
    img.bg {
        left: 50%;
        margin-left: -512px;   /* 50% */
    }
}

回答by Liam Newmarch

I know this is now an old question, but I thought I'd share a solution I came up with for anyone else who finds this question on google, like I did.

我知道这现在是一个老问题,但我想我会分享一个我想出的解决方案,供其他在谷歌上发现这个问题的人使用,就像我一样。

I was trying to get an image to cover a site's background and came across this question, however none of the solutions worked for me. I came up with this instead:

我试图获取一张图片来覆盖网站的背景并遇到了这个问题,但是没有一个解决方案对我有用。我想出了这个:

HTML: move the background image to an <img />, make it the first thing in your <body>.

HTML:移动背景图像的<img />,使它的第一件事就是在你的<body>

<html>
    <body>
        <img class="background" src="kitty.jpg" />
        <div class="content">
            ...

CSS: make the background appear under the content, set it's min-width/heightto 100%.

CSS:使背景出现在内容下方,将其设置min-width/height为 100%。

html {
    height: 100%
}

body .background {
    position: absolute;
    z-index: -1;
    min-height: 100%;
    min-width: 100%;
}

It's the min-heightand min-widthhere that does the magic. Do not give the image a width and height in the HTML or CSS, or the aspect ratio will change.

神奇的是这里min-heightmin-width这里。不要在 HTML 或 CSS 中给图像指定宽度和高度,否则纵横比会发生变化。

The above will work for IE7and IE8. If you would like to support IE6, you could set a centered image fallback like this:

以上将适用于IE7IE8。如果你想支持IE6,你可以像这样设置一个居中的图像回退:

CSS: If IE6, don't display the image, use a background image instead.

CSS: 如果IE6,不显示图像,而是使用背景图像。

body {
    _background: url("kitty.jpg") 50% top no-repeat;
}

body .background {
    _display: none;
}

(N.B. If you don't like the underscore hack to target IE6, you could use conditionalsinstead – that's what the HTML5 Boilerplatedoes.)

(注意,如果您不喜欢针对IE6的下划线攻击,您可以使用条件来代替——这就是HTML5 Boilerplate所做的。)

回答by Ned

After much trial and error, the best solution was guessing it!

经过多次试验和错误,最好的解决方案是猜测它!

The following worked for me.

以下对我有用。

body {
background-size:100%;
}

回答by Furqan Rahamath

You have two options to achieve this with just CSS:

您有两种选择可以仅使用 CSS来实现此目的:

  • Use Object-fit: cover. The only problem with this is that it will not work in all browsers
  • If you want cross browser support, you can follow primitive CSS approach:
  • 使用Object-fit: cover. 唯一的问题是它不适用于所有浏览器
  • 如果你想要跨浏览器支持,你可以遵循原始的 CSS 方法:

Position the image inside the container with absoluteand then place it right at the centreusing the combination:

使用绝对值将图像放置在容器内 ,然后使用组合将其放置在中心位置

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

Note:Since transform ONLYworks from IE9, you can make use of filters. Hereis an answer for this.

注意:由于转换适用于 IE9,因此您可以使用过滤器。是对此的答案。

Once it is in the centre, you can do,

一旦它在中心,你就可以做,

// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;

// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;

This makes the image get the effect of Object-fit:cover.

这使得图像得到了 Object-fit:cover 的效果。



Here is a demonstration of the above logic.

下面是对上述逻辑的演示。

https://jsfiddle.net/furqan_694/s3xLe1gp/

https://jsfiddle.net/furqan_694/s3xLe1gp/

回答by neil1967

Unfortunately, most solutions to this kind of problem either depend on css3 or ignore the native functionality of "cover" that preserves the original aspect ratio of the image. https://github.com/louisremi/background-size-polyfillis supposed to preserve ratio, but I could never get it to work completely when stretching the browser in certain ways (operator error, I'm sure :-) ). To solve this problem, I wrote a jquery script that I've tested on safari, chrome, ff and ie8+. You'll notice that you will have to use an img positioned absolutely instead of css background-image. Just add the bgImg as an id in the tag in html.

不幸的是,大多数此类问题的解决方案要么依赖于 css3,要么忽略了保留图像原始纵横比的“cover”的本机功能。 https://github.com/louisremi/background-size-polyfill应该保持比率,但是在以某些方式拉伸浏览器时我永远无法让它完全工作(操作员错误,我确定 :-) )。为了解决这个问题,我写了一个 jquery 脚本,我已经在 safari、chrome、ff 和 ie8+ 上测试过。您会注意到您必须使用绝对定位的 img 而不是 css background-image。只需在 html 的标签中添加 bgImg 作为 id。

CSS:

CSS:

.container { height: auto; overflow:hidden; position:relative;}
.container #bgImg { position:absolute; z-index:-1;} 

You're image selector will have to be positioned absolutely to get it to sit behind the content. That means that you're parent container has to have position: relative and then overflow: hidden so that whatever overflows from the image (since you're maintaining ratio, some pieces of it inevitable will) is hidden. Be aware also that certain display tags in the parent container will break the hiding of the overflow.

您的图像选择器必须绝对定位才能使其位于内容后面。这意味着您的父容器必须具有 position: relative 和 overflow: hidden 以便从图像中溢出的任何内容(因为您保持比例,因此不可避免地会隐藏某些部分)。还要注意父容器中的某些显示标签会破坏溢出的隐藏。

JQUERY:

查询:

$(window).load(function () {

    // only do this once and pass as function parameters, because chrome
    // and safari have trouble not only with document.ready but window.resize
    var img = new Image();
    img.src = $("#bgImg").attr('src');
    var $width_orig = img.width;
    var $height_orig = img.height;

    resizeBGImage($width_orig, $height_orig);

    $(window).resize(function () {
        resizeBGImage($width_orig, $height_orig);
    });
});

function resizeBGImage($width_img_orig, $height_img_orig) {
    // get dimensions of container
    var $width_container = $('.container').outerWidth();
    var $height_container = $('.container').outerHeight();

    // calculate original aspect ratio and ratio of the container
    var $imageratio = $width_img_orig / $height_img_orig;
    var $containerratio = $width_container / $height_container;

    var $wdiff = $width_container - $width_img_orig;
    var $hdiff = $height_container - $height_img_orig;

    // original size, so just set to original
    if (($wdiff == 0) && ($hdiff == 0)) {
        $("#bgImg").css('width', $width_img_orig);
        $("#bgImg").css('height', $height_img_orig);
    }
    // if container is smaller along both dimensions than the original image, 
    // set image to container size
    else if (($wdiff < 0) && ($hdiff < 0)) {
        $("#bgImg").css('width', $width_img_orig);
        $("#bgImg").css('height', $height_img_orig+1); // adding one because chrome can't do math
    }
    // if container is wider than long relatiave to original image aspect ratio
    // set width to container width and calculate height 
    else if ($containerratio > $imageratio) {
        $("#bgImg").css('width', $width_container);

        // calculate height using orig aspect ratio and assign to image height 
        $("#bgImg").css('height', (($width_container * $height_img_orig) / $width_img_orig) + 1); // adding one because chrome can't do math
    }
    // else container is taller than long relatiave to original image aspect ratio
    // set height to container height and calculate width
    else {
        // set the image height to container height
        $("#bgImg").css('height', $height_container + 1); // adding one because chrome can't do math

        // calculate width using orig aspect ratio and assign to image width
        $("#bgImg").css('width', (($height_container * $width_img_orig) / $height_img_orig));
    }
    $("#bgImg").css('left', (($width_container - $("#bgImg").width()) / 2).toString() + 'px');
};

Note the use of $(window).load() instead of $(document).ready(). Chrome and safari seem to have issues with the latter since in those browsers, the background image may not be fully loaded when the DOM is. Using $(window).load() ensures all window elements are in place before the script runs.

注意使用 $(window).load() 而不是 $(document).ready()。Chrome 和 safari 似乎对后者有问题,因为在这些浏览器中,当 DOM 加载时,背景图像可能无法完全加载。使用 $(window).load() 确保所有窗口元素在脚本运行之前就位。

回答by tomByrer

Sounds like you need a 'shim' or 'polyfill' like Modernizer: http://modernizr.com/docs/#html5inie

听起来你需要像 Modernizer 这样的“垫片”或“polyfill”:http: //modernizr.com/docs/#html5inie