2012-11-23 108 views
1

我正在制作一个插件,它可以对元素进行下拉菜单,并使用预定义的元素作为应用元素外部的下拉菜单。相对于另一个元素定位元素

的标记看起来像这样

<a href="javascript:void(0)" id="some-menu" data-dropdown="dropdown-element">Click</a> 

<ul id="dropdown-element"> 
    <li><a href="#">First item</a></li> 
    <li><a href="#">Second item</a></li> 
</ul> 

而且使用$("#some-menu").dropdown({ placement: 'top' });会变成#dropdown-element的下拉列表。一切都很好,很棒。

placement决定的下拉是如何根据元素(上,下,左,右)的位置,但这个应该是相当容易申请,当我想通了默认定位出来。

我尝试使用此代码引导的工具提示插件

pos = getPosition($element, inside); 

actualWidth = $this[0].offsetWidth; 
actualHeight = $this[0].offsetHeight; 

switch (inside ? placement.split(' ')[1] : placement) { 
    case 'bottom': 
     tp = {top: pos.top + pos.height, left: pos.left + pos.width/2 - actualWidth/2}; 
    break; 
    case 'top': 
     tp = {top: pos.top - actualHeight, left: pos.left + pos.width/2 - actualWidth/2}; 
    break; 
    case 'left': 
     tp = {top: pos.top + pos.height/2 - actualHeight/2, left: pos.left - actualWidth}; 
    break; 
    case 'right': 
     tp = {top: pos.top + pos.height/2 - actualHeight/2, left: pos.left + pos.width}; 
    break; 
} 

但没有运气。

这是什么样子 How the dropdown looks like in browser

这是想要的结果 How the dropdown should look like

我希望它水平居中到#some-menu,并且下拉被应用到任何元素,内联也并保持两垂直和水平定位。

编辑: 我发现下拉是一个元素中创建了position: relative,这就是为什么它的偏移是错误的。我现在的问题是将元素移动到主体中的最佳方式(或者更好的解决方案),并且保持良好的性能,而不需要更多地接触DOM。

+0

该问题的+1。此外,很好的图,但你可以添加一个你想要它看起来像吗?除非我误解了? – Basic

回答

0

这应该把菜单放在中间。

top = $('#some-menu').offset().top + 8; //Set the vertical position. 

left = $('#some-menu').offset().left - $('#dropdown-element').outerWidth/2 + $('#some-menu').outerWidth/2; //Set the menu to the center of the button. 

$('#dropdown-element').offset({top: top, left: left}); 
+0

下拉菜单不是按钮的子项,但仍应该与按钮位置相关。但是,我真正的问题是如何做到这一点真正的数学。 – fnky

+0

我编辑了我的答案,看它是否有效。 –

相关问题