2016-04-05 513 views
0

只使用普通的javascript,如何插入一個總是浮動在窗口右上角其他元素上方的按鈕?如何在JS的屏幕右上角插入浮動按鈕

到目前爲止我:

var button = document.createElement("Button"); 
button.innerHTML = "Title"; 
button.style = "margin-top:0%;right:0%;position:absolute;" 
document.body.appendChild(button); 

回答

3

使用top代替margin-top,並設置了很高的z-index

var button = document.createElement("Button"); 
 
button.innerHTML = "Title"; 
 
button.style = "top:0;right:0;position:absolute;z-index: 9999" 
 
document.body.appendChild(button);

+0

每隔回答錯過了'Z-index'一部分。 +1! – Roy

+0

如果我運行這個縮減,讓我們說堆棧溢出,該按鈕將顯示在頁面的底部,而不是頂部... – Antzi

+0

@Antzi爲什麼它的行爲呢? – LGSon

0

更改定位固定和自頂至0

button.style = "top:0%;right:0%;position:fixed;" 
2

您幾乎在那裏,但不使用margin-top屬性,而是使用top屬性並使用position:fixed;而不是position:absolute;

var button = document.createElement("Button"); 
 
button.innerHTML = "Title"; 
 
button.style = "top:0;right:0;position:fixed;" 
 
document.body.appendChild(button);