将按钮放置在元素的右上角,位置:相对

Place Button at top right corner of an element with position:relative

本文关键字:右上角 位置 相对 元素 按钮      更新时间:2023-09-26

我写了这个脚本:

var HTML_BT = '<a class="helper" href="#"><i class="icon-wrench"></i></a>';
// Append button
$("my_selector").live('mouseenter', function(){
    var 
        bt = $(this).find('a.helper'),
        pos = $(this).position();
    // Check if the button exists and creates it
    if (bt.length==0){
        bt = $(HTML_BT);
        bt.css({
            position:'absolute',
            // Calculates coordinates
            top:pos.top + 15 + 'px', 
            left:pos.left + $(this).width() - 15 + 'px'
            // .. Some other css like border, bg, color and so on.
        });
        $(this).append(bt);
    }
    // Show the button
    bt.show();
}).live('mouseleave', function(){
    var 
        bt = $(this).find('a.helper');
    // Show the button if exists
    if (bt.length!=0){
        bt.hide();
    }
});

当鼠标光标移到特定项上时,脚本在右上角显示或追加一个链接。

它工作得很好,但是我在计算放置在容器内的元素的顶部和右侧坐标时遇到了一些麻烦,这些元素已指定css位置为相对位置,因为链接坐标(正确地)计算为相对于他的容器。

.carousel-inner{
    position:relative;
}

这里我做了一个工作示例:http://jsfiddle.net/ucfKm/

有人知道如何测试,如果我必须使用绝对/相对坐标或如何获得左右位置?

谢谢你,大卫。

不需要计算它的左位置来把它放在右边和顶部只需记住绝对位置元素在相对位置元素中的位置会在父元素的左上角有它的0,0,所以:

top:15 + 'px', 
right:15 + 'px',

将你的a元素放置在距父元素顶部15px和距父元素右侧15px的位置。

小提琴更新:http://jsfiddle.net/ucfKm/5/

编辑:另外,请注意,因为你不需要计算在这种情况下的位置,你可以直接分配css的类在你的css文件,并避免不必要的javascript逻辑。

position: relative;没有将元素相对于父元素定位。它相对于元素的原始位置定位元素。

如果你想让元素位于父元素的上方和右侧15px处(只要父元素的position:设置为relative, absolutefixed),使用:

.carousel-inner{
    position: absolute;
    top: 15px;
    right: 15px;
}

如果你想让元素的位置距整个页面的顶部和右侧15px,使用:

.carousel-inner{
    position: fixed;
    top: 15px;
    right: 15px;
}

在这两种情况下,你都不需要做javascript位置计算