首页 > 解决方案 > 如何修复移动版上未覆盖整个页面的 bg 图片?

问题描述

我想为我用 Wordpress 制作的一个网站页面设置一个 bg 图像,但在移动版本上它保持其正常的纵横比。这是网站页面http://zm.jcreator.eu/

css:

.entry-content #fit {
width: 100%;
height: 100%;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;
}

The code snippet in the page editor:

<img id="fit" src="http://zm.jcreator.eu/wp- 
content/uploads/2019/03/home_1.jpg" alt="">

标签: phphtmlcsswordpressbackground

解决方案


至少有两种方法可以接近它。

1)将您的图像绝对定位在容器内。

<div class="entry-content">
  <div class="img-wrapper">
   <img id="fit" src="..." alt/>
  </div>
</div>

如果我们假设您希望您的图像占浏览器宽度和高度的 100%,那么您的 css 应该如下所示(注意我忽略了条目内容,因为我不太确定其余部分是否内容是否会在新的 div 中 - 在您的示例中似乎很不清楚)。

.img-wrapper {
    position:relative;
    width:100vw;
    height:100vh;
    overflow:hidden;
}


.img-wrapper img {
    position:absolute;
    top:50%
    left:50%;
    transform:translate(-50%,-50%);
}

这种方法的噱头——它只适用于由图像纵横比决定的某些场景。一种解决方法是使用可以在文档加载和调整大小时绑定的 JavaScript 片段。然后,您可以使用以下 JavaScript 来计算特定场景下图像的最佳尺寸:

function checkImg() {
    var img = document.getElementById('fit'));
    var section = document.getElementsByClassName('entry-content')[0];
    var imgheight = img.offsetHeight;
    var sectionheight = section.offsetHeight;
    var imgwidth = img.offsetWidth;
    var sectionwidth = section.offsetWidth;

        var imgRatio = imgheight / imgwidth;
        var scrRatio = sectionheight / sectionwidth;

        if (scrRatio > imgRatio) {
            var finalHeight = sectionheight;
            var scale = finalHeight / imgheight;
            var finalWidth = imgwidth * scale;
        } else {
            var finalWidth = sectionwidth;
            var scale = finalWidth / imgwidth;
            var finalHeight = imgheight * scale;
        }
        img.style.height = finalHeight + 'px';
        img.style.width = finalWidth + 'px';
    }
}

请记住,一旦加载文档而不仅仅是准备好就运行此函数至关重要,否则如果在加载之前执行该函数,它将无法获得正确大小的图像。

同时,如果您在调整大小时不触发它,则图像的宽度和高度不会改变。

2)使用css背景属性。正如 ArtisticPhoenix 指出的那样,您不能在图像标签上使用背景属性。但是,您可以将图像设置为元素的背景。然后你可以使用以下内容:

<div class="entry-content">
  <div class="img-wrapper">
  </div>
</div>

请注意,您不会将图像与 img 标签一起放在这里,而是必须在 CSS 中指定 background-image 属性的来源,如下所示:

.img-wrapper {
    position:relative;
    width:100vw;
    height:100vh;
    overflow:hidden;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: center;
    background-size: cover;
    background-image:url('http://zm.jcreator.eu/wp-content/uploads/2019/03/home_1.jpg');
}

由于您使用的是 WordPress,因此您可能希望使用您在 CMS 中选择的图像。在这种情况下,您只需要使用内联样式指定背景图像:

<div class="entry-content">
  <div class="img-wrapper" style="background-image:url('<?php echo your_php_function_to_get_img_url(); ?>')">
  </div>
</div>

推荐阅读