在创建要与 scrollTo-Plugin 等一起使用的单页布局时,我遇到了同样的问题。页面布局分为两部分:左侧为背景图像,应随内容更改/滚动在右侧。所以我曾经制作一种jquery插件来结合“背景位置:固定”和“背景尺寸:封面”。您只需要按类/ID 定义元素即可对齐背景图像。
不要抱怨代码。我对 javascript/jquery 比较陌生。但它的工作;)它是:
function fixedResize() {
    var targetEl = $('element where bg-images are in');
    var targetWidth = targetEl.width();
    var targetHeight = targetEl.height();
    var targetPosX = targetEl.offset().left;
    var targetPosY = targetEl.offset().top;
    var leftRatio = targetWidth / targetHeight;
    //console.log('TargetWidth', targetWidth, 'TargetHeight', targetHeight, 'Offset', targetPosX, targetPosY, 'leftRatio', leftRatio);
    targetEl.each(function(){
        var imgTarget = $(this);
        var url = $(this).css('background-image').replace('url(', '').replace(')', '').replace("'", '').replace('"', '');
        var bgImg = $('<img />'); // make background-image as image tag for getting width and height of the image
        imgTarget.css('background-attachment','fixed');
        bgImg.hide();
        bgImg.bind('load', function(){
            var imgHeight = $(this).height();
            var imgWidth = $(this).width();
            var imgRatio = imgWidth / imgHeight;
            $(this).remove(); // remove img Tags again
            // Calculate resize dimensions
            if (imgRatio > leftRatio) {
                var currentWidth = imgRatio * targetHeight; // image width after resize
                var currentHeight = (currentWidth/imgWidth)*imgHeight;
                var setToLeft = ((currentWidth - targetWidth)/2);
                var imgPosX = targetPosX - setToLeft;
                var imgPosY = (currentHeight - targetPosY - currentHeight/2 - targetHeight/2)* -1;
                var resizeImg = 'background-size: auto '+ targetHeight +'px;';                  
                } else if (imgRatio < leftRatio){
                    var currentWidth = targetWidth;
                    var currentHeight = (currentWidth/imgWidth)*imgHeight;
                    var imgPosX = targetPosX;
                    var imgPosY = (currentHeight - targetPosY - currentHeight/2 - targetHeight/2)* -1;
                    var resizeImg = 'background-size: '+ targetWidth +'px auto;'; // resize background
                }
            imgTarget.attr('style','background-attachment: fixed; background-position: '+ imgPosX +'px '+ imgPosY +'px;' + resizeImg);
            console.log('imgWidth', imgWidth, 'imgHeight', imgHeight, 'imgRatio', imgRatio, 'currentWidth', currentWidth, 'currentHeight', currentHeight, 'setToLeft', setToLeft);
            console.log('imgPos', imgPosX, imgPosY, 'setToLeft', setToLeft, targetPosX);
        });
        $(this).append(bgImg);
        bgImg.attr('src', url);
    });
}
fixedResize(); // initiate function
$(window).resize(function() {
    fixedResize(); // initiate function for window resize (Fluid behavior)
});
或
jsfiddle.net/rowphant/eXb6e/14/