使用JavaScript更改了固定HTML元素的位置

时间:2017-09-08 15:10:20

标签: javascript html css

我想知道是否可以使用" position:fixed;"来移动div或其他元素。我希望它不受滚动的影响,我可能会设置它,所以你可以通过点击和拖动来移动它,但我甚至无法让它变成预算。是"固定"这些元素无法做到这一点?

#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 个答案:

答案 0 :(得分:2)

尝试:

d.style.left = d.style.left + 2 + 'px'; 
d.style.top = '5px';  

您需要指定值单位(像素,例如),检查其他单位的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

答案 1 :(得分:-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>