我有一个必须与页面元素相关的正文背景(#container)。 当页面调整大小(较小的宽度)时,容器向左移动(因为它居中)。背景也应该向左移动相同的数量。
现在我有以下代码,它适用于我的问题:
/*
* The background must be relative to the rest of the page elements.
* The background position.left = 0px when the offset.left of the container = 362.
* The new background position.left is based on the current position of the container.
*/
var beginBackgroundPositionLeft = 362;
function changeBackgroundPosition() {
var newLeft = jQuery("div.container").offset().left;
newLeft = (-1 * beginBackgroundPositionLeft + newLeft) + "px";
jQuery("body").css("background-position", newLeft + " 0px");
}
jQuery(window).resize(function(e){
console.log(e);
// Change the position of the background
// when resizing the window.
changeBackgroundPosition();
});
jQuery(document).ready(function() {
// Change the position of the background on entering the page..
// Is needed because we don't know the resolution of the user so it can't be done with css.
changeBackgroundPosition();
});
它工作正常,但在高度调整浏览器大小时也会执行。如何检查浏览器是否水平调整大小,以便可以忽略调整高度?
当然可以保存当前的窗口宽度,并检查是否有更改,但我正在寻找更好的方式(并学习一些我还不知道的东西;))!
正如你所看到的,我已经记录了调整大小功能的'e',但找不到对我有用的东西..
希望了解您的建议。谢谢!
答案 0 :(得分:1)
如果仅更改窗口宽度,这就是我“做某事”的方式。调整大小事件对象中没有太多东西让你以更好的方式检测到这一点我害怕。也许你可以在background-position CSS属性中尝试使用百分比找到一些东西:
var $window = $(window),
w = $window.width();
$window.resize(function(e) {
if (w = $window.width() == w) {
return;
}
console.log('width changed');
});
答案 1 :(得分:1)
我希望你知道你也可以通过CSS设置背景图像。
background-position: center top; /* first value is horizontal alignment second is vertical*/
background-position: center center;
background-position: center bottom;
或者您也可以用百分比指定背景位置。
我不知道是否有任何可能只解决水平调整大小的问题,除了你已经提到的那个(保存当前窗口宽度并进行比较)。我没有看到您建议的解决方案有问题。如果有更好的方法,任何人都会纠正我。
答案 2 :(得分:0)
等等,所以body { background:#fff url(bg.jpg) no-repeat 50% 0; }
没有削减它?