2011-08-19 59 views
0

我有一個正文背景,必須是相對於頁面元素(#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」,但它無法找到任何有用到我..

希望瞭解您的建議什麼的。謝謝!

回答

1

如果只改變了窗口寬度,這就是我要做的事。調整大小事件對象中沒有太多,讓我們以更好的方式檢測到這一點。也許你可以在背景位置的CSS屬性的百分比嘗試找到:

var $window = $(window), 
    w = $window.width(); 

$window.resize(function(e) { 
    if (w = $window.width() == w) { 
     return; 
    } 
    console.log('width changed'); 
}); 
1

我希望你知道,你也可以設置通過CSS中心的背景圖像。

background-position: center top; /* first value is horizontal alignment second is vertical*/ 
background-position: center center; 
background-position: center bottom; 

或者你也可以指定百分比的背景位置。

我不知道任何可能只解決水平調整大小,除了你已經提到的(保存當前窗口寬度和比較它)。我沒有看到您的建議解決方案的問題。如果有更好的方法,任何人都會糾正我。

+0

我知道CSS選項,但它不是這種情況下的最佳方式..(還有更多的JS與bg相關,所以這是一個很好的補充) – NickGreen

0

等等,那麼body { background:#fff url(bg.jpg) no-repeat 50% 0; }不會削減它?

+0

不,因爲容器有寬度。因此,當瀏覽器被調整至一較低的寬度則容器,背景被移動到左邊。人體不能在我的情況下,寬度..此問題的解決方案是一個絕對定位的div寬度相同的容器,但是這也不是我的情況下,選擇(我在一些交付需求有限;) ) – NickGreen

相關問題