如何在初始加载时将背景图像设置为“background-size:contain”,但在窗口调整大小时防止其重新调整大小?

3

有没有什么方法可以做到这一点?我正在创建一个 HTML 应用程序,当软键盘打开时,我不希望背景图片调整大小。谢谢!


1
是的,这是可能的。请展示你的代码/JSFiddle。 - atmd
3个回答

0

.element{
    /*important*/
    width: [you-width];
    height: [you-height];
    /*image*/
    background-image: url(some.jpg);
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-position: 0 0;
    /*optional*/
    position: relative;
    background-attachment: fixed;
    overflow: hidden;
}


0

谢谢大家,我是这样解决的:

$scope.getImageSize = function(div){
var backgroundImage = new Image();
backgroundImage.src = $(div).css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");

backgroundImage.onload = function() {
    var width = this.width;
    var height = this.height;

    var object = $(div);

    /* Step 1 - Get the ratio of the div + the image */
    var imageRatio = width/height;
    var coverRatio = object.outerWidth()/object.outerHeight();

    /* Step 2 - Work out which ratio is greater */
    if (imageRatio >= coverRatio) {
        /* The Height is our constant */
        var coverHeight = object.outerHeight();
        var scale = (coverHeight / height);
        var coverWidth = width * scale;
    } else {
        /* The Width is our constant */
        var coverWidth = object.outerWidth();
        var scale = (coverWidth / width);
        var coverHeight = height * scale;
    }
    var cover = coverWidth + 'px ' + coverHeight + 'px';
    $localStorage.image = {width: coverWidth + "px", height: coverHeight + "px"};
    $('.pane').css('backgroundSize', $localStorage.image.width + " " + $localStorage.image.height);
    return $localStorage.image;
};

}

由于这是一个移动应用程序,我锁定了方向,因此假设宽度和高度不会改变,我将background-size更改为与从background-size: contain调整大小的宽度和高度相等。


0

你可以使用JS...当你触发键盘的显示时,你可以在该元素上添加一个类,并为BG设置一个固定值


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接