2012-01-19 118 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) 

希望这将解决您的问题。

相关问题