Javascript 正文背景位置必须相对于页面元素
我有一个body背景,它必须与页面元素(#container)相关。 调整页面大小(宽度较小)时,容器会向左移动(因为它居中)。背景也应该以相同的数量向左移动 现在我有了以下代码,可以解决我的问题:Javascript 正文背景位置必须相对于页面元素,javascript,jquery,background,resize,Javascript,Jquery,Background,Resize,我有一个body背景,它必须与页面元素(#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 =
/*
* 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”,但在其中找不到任何对我有用的内容
希望能从你的建议中学到一些东西。谢谢 如果只改变窗口宽度,我就会这样“做”。在resize事件对象中,恐怕没有多少东西可以让您以更好的方式检测到这一点。也许您可以在“背景位置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)不重复50%0;}
不会切断它吗?我知道CSS选项,但对于这种情况,这不是最好的方法。。(还有更多与bg相关的JS,因此这是一个不错的添加)不,因为容器有一个宽度。因此,当浏览器的大小调整到低于容器的宽度时,背景会向左移动。在我的情况下身体不能有宽度。。这个问题的一个解决方案是使用与容器宽度相同的绝对定位div,但在我的情况下,这也不是一个选项(我在一些已交付的需求中受到限制;)