2017-09-08 78 views
0

我想知道是否可以使用「position:fixed」移動div或其他元素。我希望它不受滾動的影響,我可能會設置它,所以你可以通過點擊和拖動來移動它,但我甚至不能讓它變動。 「固定」元素無法做到這一點?使用JavaScript更改了固定HTML元素的位置

#menu { 
    position:fixed; 
    margin-top: -110px; 
    margin-left: 300px; 
    //its now top:110px; left:300px; 
} 
<TABLE id="menu"> 
    my menu here 
</TABLE> 

<script type="text/javascript"> 
    var d = document.getElementById('menu'); 
    d.style.left =d.style.left+2; //doesn't work 
    d.style.top = '5'; // doesn't work 
</script> 

回答

2

嘗試:

​​

您需要指定值單元(像素例如),檢查this文件的其他單位。

var menu = document.getElementById('menu'); 
 
var unit = document.getElementById('unit'); 
 
var offset = 0; 
 

 
menu.style.top = '5px'; 
 

 
function move(){ 
 
    offset += 20; 
 
    menu.style.left = offset + unit.value; 
 
}; 
 

 
function reset(){ 
 
    offset = 0; 
 
    menu.style.left = '0px'; 
 
};
#menu { 
 
    width: 200px; 
 
    background-color: blue; 
 
    position:fixed; 
 
    color: white 
 
}
<div id="menu"> 
 
    my menu here 
 
</div> 
 
<br/> 
 
<span>Unit</span> 
 
<select id="unit"> 
 
    <option value="px">px</option> 
 
    <option value="em">em</option> 
 
    <option value="ex">ex</option> 
 
    <option value="%">%</option> 
 
    <option value="cm">cm</option> 
 
    <option value="mm">mm</option> 
 
    <option value="in">in</option> 
 
    <option value="pt">pt</option> 
 
    <option value="pc">pc</option> 
 
</select> 
 
<br/> 
 
<button onclick="move()">Move</button> 
 
<button onclick="reset()">Reset</button> 
 
<br/> 
 
Play with "Move" and "Reset" buttons to see the difference between units

+0

哎,當然!!非常感謝您的快速響應。 – EndUserAbuser

+0

歡迎你的朋友,很高興幫助,現在更新了你可以用不同的單位玩的例子:) – codtex

+0

該死的我喜歡「運行代碼片段」功能,這是偉大的@codtex – EndUserAbuser

-1
try the below code, it is working for me. You can see that the 2px margin in the inline style in developer tools 

<!DOCTYPE HTML> 
 
<html> 
 

 
<head> 
 
    <meta charset="utf-8"> 
 
    <meta lang="en"> 
 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
 
</head> 
 
<style> 
 
    #menu { 
 
    position: fixed; 
 
    margin-top: 110px; 
 
    margin-left: 300px; 
 
    } 
 
</style> 
 

 
<body> 
 

 
    <table id="menu"> 
 
    <tbody> 
 
     <tr> 
 
     <td>one</td> 
 
     <td>two</td> 
 
     <td>three</td> 
 
     </tr> 
 

 
    </tbody> 
 
    </table> 
 

 
    <script type="text/javascript"> 
 
    var d = document.getElementById('menu'); 
 
    d.style.left = d.style.left + 2 + "px"; 
 
    d.style.top = '5' + "px"; 
 
    </script> 
 
</body>

+0

是的,我需要「px」我很想把這個問題放在一個令人尷尬的問題上。感謝您的回答。 – EndUserAbuser