2010-08-30 69 views
0

這是我的問題,我有一個div,裏面有2個div,一個居中,另一個固定在左邊,問題是當我調整屏幕大小時,居中的div與固定的div重疊,我想要做的是檢測當居中的div與其他div重疊並用javascript更改其左側值時,但沒有工作,有什麼想法?用javascript移動div

這是我的設計:

<div id="content-wrap"> 
    <div id="content"> 
    </div> 
    <div id="leftbar"> 
    </div> 
</div> 

和CSS:

#content-wrap 
{ 
    clear: both; 
    float: left; 
    width: 100%; 
} 
#content 
{ 
    text-align: left; 
    padding: 0; 
    margin: 0 auto; 
    height: 470px; 
    width: 760px; 
    overflow: auto; 
} 
#leftbar 
{ 
    background-color: transparent; 
    width: 200px; 
    height: 470px; 
    position: absolute; 
    top: 185px; 
    left: 50px; 
} 

,這是javascript代碼:

window.onload = function Centrar() { 
    var leftBar = $get("leftbar"); 

    if (leftBar != null) { 
     var content = $get("content"); 
     var size = leftBar.offsetLeft + leftBar.offsetWidth; 
     if (content.offsetLeft < size) {    
      content.style.left = size + 20 + 'px'; 
      }    
    } 
} 

預先感謝任何幫助。

+0

你不需要追加'px'。 – Fosco 2010-08-30 12:18:42

+0

如果我不添加'px',div的屬性「left」不會被修改。 – Argons 2010-08-30 12:23:31

+0

Fosco,左側的CSS值需要px,除非值爲0. – Lekensteyn 2010-08-30 12:26:28

回答

1

最簡單的解決將是應用min-width#content-wrap容器防止發生重疊:

#content-wrap { 
    clear: both; 
    float: left; 
    width: 100%; 

    /* #leftbar width x 2 + #content width */ 
    min-width: 1160px; 
} 

但是,如果你想使用JavaScript,你需要將代碼附加到窗口負載和調整事件:

$(window).bind('load resize', function() { 
    var content = $('#content'); 
    var leftbar = $('#leftbar'); 

    // get the right edge of the #leftbar 
    var leftbarEdge = leftbar.width() + leftbar.offset().left; 

    // check if an overlap has occured and adjust #content left position if yes 
    if (leftbarEdge > content.offset().left) { 
     content.css({ 
      left: leftbarEdge - content.offset().left 
     }); 
    } 
}); 

你需要申請得到這個工作是設置#contentposition: relative在CSS所以它尊重left屬性喲最後改變你用Javascript設置:

#content { 
    position: relative; 
    /* remaining css */ 
} 

你可以看到它in action here

+0

OP似乎沒有使用jQuery。 – lincolnk 2010-08-30 13:35:20

+1

我注意到在OP的代碼片段中,但問題是用jQuery標記的,所以我想了解爲什麼不。最終,他們應該通過在他們的'#content' CSS中增加'position:relative'來工作。 – Pat 2010-08-30 13:56:15