[英]Body background position must be relative to a page element
我有一个身体背景,必须相对于页面元素(#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',但找不到对我有用的东西..
希望了解您的建议。 谢谢!
如果仅更改窗口宽度,这就是我“做某事”的方式。 调整大小事件对象中没有太多东西让你以更好的方式检测到这一点我害怕。 也许你可以在background-position CSS属性中尝试使用百分比找到一些东西:
var $window = $(window),
w = $window.width();
$window.resize(function(e) {
if (w = $window.width() == w) {
return;
}
console.log('width changed');
});
我希望你知道你也可以通过CSS设置背景图像。
background-position: center top; /* first value is horizontal alignment second is vertical*/
background-position: center center;
background-position: center bottom;
或者您也可以以百分比指定背景位置。
我不知道是否有任何可能只解决水平调整大小,除了你已经提到的那个(保存当前窗口宽度并进行比较)。 我没有看到您建议的解决方案有问题。 如果有更好的方法,任何人都会纠正我。
等等,所以body { background:#fff url(bg.jpg) no-repeat 50% 0; }
body { background:#fff url(bg.jpg) no-repeat 50% 0; }
不剪?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.