Mat*_*ijs 1 html javascript css
我正在尝试更改绝对定位 div 的左侧位置。该样式是使用以下内容在 css 中预先声明的:
#menu {
position:absolute;
width:200px;
min-height:40%;
left:-200px;
}
Run Code Online (Sandbox Code Playgroud)
现在,当我尝试使用 javascript 检查 的值时left,它显示为"". 下面的JS用于检查值:
var menuElement = document.getElementById('menu');
console.log(menuElement.style.left);
Run Code Online (Sandbox Code Playgroud)
我已经设置了这个 codepen作为演示。请注意,对于负左值和正左值都会发生这种情况。
为什么左边的值总是""?
就此而言,任何样式元素似乎都显示为""。为什么会发生这种情况?
您必须使用getComputedStyle()来获取通过样式表声明的规则。
var menuElement = document.getElementById('menu');
var menuElement2 = document.getElementById('menu2');
console.log(getComputedStyle(menuElement).left);
console.log(getComputedStyle(menuElement2).left);
console.log(getComputedStyle(menuElement));
console.log(getComputedStyle(menuElement));Run Code Online (Sandbox Code Playgroud)
#menu {
position: absolute;
width: 200px;
min-height: 40%;
left: -200px;
background-color: black;
}
#menu2 {
position: absolute;
width: 200px;
min-height: 40%;
left: 200px;
background-color: black;
}Run Code Online (Sandbox Code Playgroud)
<div id="menu"></div>
<div id="menu2"></div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
309 次 |
| 最近记录: |