我想做的就是使用这部分jQuery将图像居中。我图像的选择器是“ .section-header img”。

var image_center = function(){

    var imageWidth = $('.section-header img').width();
    var windowWidth = $(window).width();
    var centerFix = -(imageWidth-windowWidth)/2 ;

    console.log(imageWidth, windowWidth, centerFix);

    $('.section-header img').css({'left': centerFix});


}


当文档准备好并调整窗口大小时,我调用该函数:

$(document).ready(function(){

    image_center();

    $(window)resize(function(){
        image_center();
    }


我的问题是,在窗口最初加载时,我无法使该功能正常工作。在我的控制台中查看,浏览器读取的图像具有与浏览器相同的宽度。调整浏览器大小后,便会读取图像的实际宽度。 Chrome内置的某些功能会在这里绊倒我吗?有没有更简单的方法可以做到这一点(不使用背景图片)?

谢谢,

心肺复苏术

最佳答案

使用CSS进行这项工作可能会更容易。

.section-header {
     background-image: url("/path/to/image.jpg");
     background-position: center;
     background-size: contain;
     background-repeat: no-repeat;
}

10-05 20:31
查看更多