Javascript - 改变位置的问题
Javascript - Problems to change the Position
我尝试使用 Javascript 更改位置顶部 (CSS) 值。我的元素有一个绝对位置 (top: -300px;
)。但是我无法设置我的 div 的 px...你可以在下面的代码中看到,我试过的版本,只设置为 0 工作所有其他版本不会影响我的 div-位置。
var value = -35;
document.getElementById("myElement").style.top = value; // Doesn't work
document.getElementById("myElement").style.top = value + 'px'; // Doesn't work
document.getElementById("myElement").style.top = 0; // Work
document.getElementById("myElement").style.top = '10px'; // Doesn't work
document.getElementById("myElement").style.top = '10'; // Doesn't work
所以问题是:我的代码有什么问题,如何更改 "top" 属性的值?
它运行完美。
document.getElementById("myElement").style.top = '100px';
检查下面的代码片段。
document.getElementById("myElement").style.top = '100px';
button{
width:100px;
height:50px;
padding:10px;
background:aqua;
border-radius:10px;
position:absolute;
}
<button id="myElement">Watch me</button>
如果以后有人遇到同样的问题,我自己的这个答案可能会有所帮助:
我找到了解决方法。这是因为值 0 > make 问题,所以如果您的值低于 0,只需使用 parseInt:
document.getElementById("myElement").style.top = parseInt(value) + 'px';
感谢大家的帮助,这个问题现在可以关闭了
我尝试使用 Javascript 更改位置顶部 (CSS) 值。我的元素有一个绝对位置 (top: -300px;
)。但是我无法设置我的 div 的 px...你可以在下面的代码中看到,我试过的版本,只设置为 0 工作所有其他版本不会影响我的 div-位置。
var value = -35;
document.getElementById("myElement").style.top = value; // Doesn't work
document.getElementById("myElement").style.top = value + 'px'; // Doesn't work
document.getElementById("myElement").style.top = 0; // Work
document.getElementById("myElement").style.top = '10px'; // Doesn't work
document.getElementById("myElement").style.top = '10'; // Doesn't work
所以问题是:我的代码有什么问题,如何更改 "top" 属性的值?
它运行完美。
document.getElementById("myElement").style.top = '100px';
检查下面的代码片段。
document.getElementById("myElement").style.top = '100px';
button{
width:100px;
height:50px;
padding:10px;
background:aqua;
border-radius:10px;
position:absolute;
}
<button id="myElement">Watch me</button>
如果以后有人遇到同样的问题,我自己的这个答案可能会有所帮助: 我找到了解决方法。这是因为值 0 > make 问题,所以如果您的值低于 0,只需使用 parseInt:
document.getElementById("myElement").style.top = parseInt(value) + 'px';
感谢大家的帮助,这个问题现在可以关闭了