1

I'm making a plugin that makes a dropdown on an element and use a pre-defined element as the dropdown menu outside the applied element.

The markup looks like this

<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>

And using $("#some-menu").dropdown({ placement: 'top' }); will turn #dropdown-element to a dropdown. All good and dandy.

placement decides on how the dropdown is positioned according to the element (top, bottom, right, left) but this should be fairly easy to apply, when I have figured the default positioning out.

I tried using this code from Bootstrap's Tooltip plugin

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;
}

But without luck.

This is what it looks like How the dropdown looks like in browser

And this is the wanted result How the dropdown should look like

I want it horizontally centered to #some-menu and the dropdown to be applied to any element, inlines too and keep both the vertical and horizontal positioning.

Edit: I found out that the dropdown was created inside a element with position: relative, which is why its offset is wrong. My question is now what the best way to move the element into the body (or perhaps a better solution for this) and keep good performance without touching the DOM more than needed.

4

1 回答 1

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});
于 2012-11-23T17:15:42.837 回答