jQuery UI相对于两个元素的位置

FtL*_*Lie 9 javascript jquery position jquery-ui

是否可以指定jQuery UI位置,其中X坐标相对于element1而Y坐标相对于element2?

示例1:我想弹出一个对话框,使其水平居中,但垂直居中于其他元素.

示例2:我的DOM中有两个项目,我想在这两个项目的外角放置第三个项目.我知道我可以选择每个人的位置,并从另一个中使用x和y,但是看起来更好看

jQuery('#UpperRight').postion({ 
    my : 'right top',
    at : 'right',
    of : '#rightMostItem',    
    at : 'top',
    of : '#topMostItem'
}) // double parameters don't work of course
Run Code Online (Sandbox Code Playgroud)

要么

jQuery('#UpperRight').position({ 
    my : 'right IGNORE',
    at : 'right IGNORE',
    of : '#rightMostItem'})
 .postion({ 
    my : 'IGNORE top',
    at : 'IGNORE top',
    of : '#topMostItem'
}); // where IGNORE overrides the default center
Run Code Online (Sandbox Code Playgroud)

到目前为止所有尝试都被困在"中心"作为默认值,不允许使用"我在一个方向上的当前位置"作为基础.任何好的想法都非常好!

Ric*_*cee 5

这是一个快速的 jquery 插件,如果我正确理解你的问题,它可以完成你想要的事情。

http://jsfiddle.net/S4N5g/5/

插件代码:

$.fn.positionRelative = function(config) {
    var element = this;
    var config = config || {};
    var x = config.x || false;
    var y = config.y || false;    
    var of = config.of || false;

    var css = {}, positionX, positionY;
    
    if (x !== false) {
        
        var offsetX = of.offset().left;
        if (x === 'left') {
            positionX = offsetX;
        } else if(x === 'center') {
            
            var elWidth = element.width();
            var elOffsetWidth = elWidth / 2;
            
            positionX = offsetX + (of.width() /  2);
            positionX = positionX - elOffsetWidth;
            
        } else if(x === 'right') {
            positionX = offsetX + of.width();
        }
        css['left'] = positionX + 'px';
    }

    if (y !== false) {
        var offsetY = of.offset().top;
        
        if (y === 'top') {
            positionY = offsetY;
        } else if(y === 'center') {
            
            var elHeight = element.height();
            var elOffsetHeight = elHeight / 2;
            
            positionY = offsetY + (of.height() /  2);
            positionY = positionY - elOffsetHeight;
            
        } else if(y === 'bottom') {
            positionY = offsetY + of.height();
        }        
        css['top'] = positionY + 'px';        
    }

    css['position'] = 'absolute';
    element.css(css);
    return this;
}
Run Code Online (Sandbox Code Playgroud)

用法:

//Usage
$('.popup').positionRelative({
    x: 'center',
    of: $('.element1')
}).positionRelative({
    y: 'center',
    of: $('.element2')
});
Run Code Online (Sandbox Code Playgroud)

您还可以使用选项left, rightor centerforxtop, bottom, centerfor y