2012-01-19 132 views
0

如何根據絕對定位的div是否超出其容器格來指定絕對左側0px或絕對右側0px。絕對位置元素左側還是右側取決於它的位置?

我想我的意思是一個簡單的例子:右鍵單擊您的瀏覽器,看到它的菜單位置在您點擊的位置右側,而不是一直走到頁面右側,而不是在頁面之外,它保持在它的內部,所以它仍然可見。

例如:(超過盒懸停) http://jsfiddle.net/ueSNQ/1/

+0

嘗試位置:相對 – AmGates

+0

我猜想一個簡單的例子,我的意思是:右鍵單擊您的瀏覽器,看到它的菜單位置在您點擊的位置右側,而不是一直走到右側頁面,而不是在頁面之外,它保持在它的內部,所以它仍然可見。 –

+0

@DylanCross首先是上下文菜單的內置算法。爲了做這樣的事情,你必須在div的offsetWidth offsetHeight鼠標的位置和客戶端的寬度和高度之間建立一個公式。然後在計算鼠標當前位置的左上角或右下角是否有足夠的空間後設置位置。 – khael

回答

3

這聽起來像你需要使用腳本工作的「取決於如果絕對定位div將超出其容器div」位,IE支持css表達式,但你可能是在跨瀏覽器解決方案之後。

是說,這應該是一些簡單的事情這樣

function isOverflow(parent, child){ 
    var left = 0; 
    var op = child; 
    while(op && op != parent){ 
     left += op.offsetLeft; 
     op = op.offsetParent; 
    } 

    return ((left + child.offsetWidth) > parent.offsetWidth); 

} 

function getHoverHandler(parent, child){ 
    return function(){ 
     if(isOverflow(parent, child)){ 
      child.style.marginLeft = 'auto'; 
      child.style.right = '0px'; 
      child.style.left = ''; 
     } 
    } 
} 

function attach(o,e,f){ 
    if(o.addEventListener){ 
     o.addEventListener(e, f, false); 
    }else if(o.attachEvent){ 
     o.attachEvent('on'+e,f); 
    } 
} 

var yellowElement = document.getElementsByTagName('UL')[0]; 
var list= document.getElementsByTagName('LI'); 
for(var i = 0; i < list.length; i++){ 
    var element = list[i]; 
    var tip = element.getElementsByTagName('DIV')[0]; 
    attach(element, 'mouseover', getHoverHandler(yellowElement,tip)); 

} 
+0

添加示例。 –

1

那麼首先如果容器div有設定爲比position: absolute, right: 0pxleft: 0px將相對定位到容器的位置的位置。否則,它將定位到第一個父節點上,從想要的具有位置的div開始,如果沒有找到它,它將與身體有關。因此,您可以搜索具有位置設置的第一個父容器或祖父容器。這個問題很難理解,所以如果你想分享一些我們樂於提供幫助的例子。

編輯:

在你的貼吧是exactley就像我的評論的例子,計算母公司的offsethWidth和offsetWidth +左鍵不被溢出,如果它是降低左側或只是刪除離開,並設置正確的定位。對於寬度和高度相同的效果,你必須爲角落做一些事情。

+0

增加了一個例子。 –

+0

@DylanCross我編輯了這篇文章。希望你沒有任何代碼就明白了。 – khael

1

好吧朋友, 嘗試以下步驟

1. You have a container div and on right clicking on it you will need to display a div for example say div with list of menus. 
2. Have the left position of the container div in a variable **contLeft** and width of the container in another variable **contWidth** 
3. Assign the oncontextmenu event handler on the container div. 
4. In the event handler function take the mouse x postion in a variable **mosX** and mouse y position in a variable **mosY** and you have to fix the top position of the div to be displayed as mosY and the left as mosX. 
5. In order to maintain the div within the container you have to calculate the container's screen occupation as **totPos = (contLeft + contWidth)** 
6. Calculate the screen occupation of the menu div as **posMenu = (mosX + width of the div)** 
7. If the totPos greater than or equal to posMenu display the menu in the same top and left postion using the values of mosY and mosX 
8. Else place the menu in position top = mosY and left = (mosX - width of menu div) 

希望這將解決您的問題。

相關問題