我有一個正文背景,必須是相對於頁面元素(#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」,但它無法找到任何有用到我..
希望瞭解您的建議什麼的。謝謝!
我知道CSS選項,但它不是這種情況下的最佳方式..(還有更多的JS與bg相關,所以這是一個很好的補充) – NickGreen