![](/img/trans.png)
[英]How to position the DataTables button up to the top right corner of the browser?
[英]Place Button at top right corner of an element with position:relative
我寫了這個腳本:
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/
有人知道如何測試我是否必須使用絕對/相對坐標,或者如何獲得右左位置?
非常感謝Davide。
請記住,相對定位的元素內絕對定位的元素將在父元素的左上角具有0,0,而不是計算將其置於右側和頂部的左位置。
top:15 + 'px',
right:15 + 'px',
將您的元素放置在距離父級頂部15像素和距離父級右側15像素的位置。
小提琴更新: http : //jsfiddle.net/ucfKm/5/
編輯:另外,請注意,由於在這種情況下不必計算位置,因此可以將css直接分配給css文件上的類,並避免不必要的javascript邏輯。
position: relative;
不會相對於父元素放置元素。 它將元素相對於該元素的原始位置定位。
如果要將元素放置在距離父級頂部和右側15像素的位置(只要父級的position:
設置在其自身上,其值可以是relative
, absolute
或fixed
),請使用:
.carousel-inner{
position: absolute;
top: 15px;
right: 15px;
}
如果您希望元素位於整個頁面頂部和右側15像素的位置,請使用:
.carousel-inner{
position: fixed;
top: 15px;
right: 15px;
}
無論哪種情況,您都無需進行javascript位置計算。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.