我写了这个脚本:
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();
}
});
当鼠标光标移到特定元素上时,脚本会在上/右 Angular 显示或附加一个链接。
它工作正常,但我在计算放置在已将 css 位置指定为相对位置的容器内的元素的顶部和右侧坐标时遇到了一些麻烦,因为链接坐标(正确地)计算为相对于他的容器。
.carousel-inner{
position:relative;
}
我在这里做了一个工作示例:http://jsfiddle.net/ucfKm/
有人知道如何测试我是否必须使用绝对/相对坐标或如何获得左右位置?
非常感谢,大卫。
最佳答案
与其计算左侧位置以将其放在右侧和顶部位置,不如记住相对定位元素内的绝对定位元素的 0,0 位于父元素的左上角,因此:
top:15 + 'px',
right:15 + 'px',
会将您的 a 元素定位在距父级顶部 15 像素和距父级右侧 15 像素的位置。
fiddle 更新:http://jsfiddle.net/ucfKm/5/
编辑:另外,请注意,因为在这种情况下您不必计算位置,您可以将 css 直接分配给 css 文件上的类,并避免不必要的 javascript 逻辑。
关于javascript - 将按钮放在位置为 :relative 的元素的右上角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15927160/