本文介绍了根据浏览器宽度移动背景图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.leavesbg {
  background: #f7fff7 url(/images/leaves4.png) repeat-y fixed 480px top;
}

因此,如果页面的浏览宽度超过800px,我会喜欢将bg图像向右移动一半。也就是说,如果他们在1024x640中查看它,我想在宽度上添加112((1024-800)/ 2)(所以 ...固定592px顶部;

So if the page is being viewed at greater than 800px wide, I'd like to move the bg image half that much further to the right. That is to say, if they were viewing it in 1024x640 for example, I'd like to add 112 ((1024-800)/2) to the width (so ... fixed 592px top;

这是我的jquery试图移动它

Here's my jquery attempt to move it

function moveBG() {
    var bgoffset =480;
    var pagewidth = $('body').width();

    if (pagewidth>800) {
        bgoffset=pagewidth-bgoffset;
        bgoffset=bgoffset/2;
    }
    $('.leavesbg').css(background-position: bgoffset +'px top');
}


    $(document).ready(function(){
    moveBG();
    $(window).resize(moveBG);

});

我希望我只是忘记简单的事情,但我仍然是jQuery的新手。

I expect I'm just forgetting something simple, but I'm still relatively new to jQuery.

推荐答案

bgoffset=bgoffset+'px top';
$('.leavesbg').css('background-position', bgoffset );

所以我这样做了我的原始数学错误(但这与实际问题并不十分相关),但据我所知,我的代码中的实际错误是改变css行,我认为这是有效的。可能有一个更好,更有效的方法,然后我上面的鹅卵石,所以我仍然欢迎如何更好地编码它的建议。
谢谢。

So I was doing some of the original math wrong (but that's not terribly relevant to the actual question), but as far as I can tell the actual error in my code was the "change the css" line, and I think this works. There's probably a better and more efficient way to to this then the cobble I have have above, so I'd still welcome suggestions for how to code it better.Thanks.

这篇关于根据浏览器宽度移动背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 12:25