<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box{background-color: black;};
.box1{height: 600px;}
/* 为啥.box1样式出不来? */
</style>
<script>
window.onload = function(){
var oDiv = document.getElementById("box");
alert(oDiv.currentStyle['height'])
alert(getComputedStyle(oDiv)["height"])
//为啥同时两个alert的时候不能alert出第一个?
// alert (getStyle("height", oDiv))
}
// function getStyle(x, y){
// return y.currentStyle ? y.currentStyle[x]:getComputedStyle(y)[x]
// }
/* 这个函数的node和cssstyle都只是语义化标签,并没有给他们赋值,为什么能够说node就是一个标签下面的,cssstyle就是与之对应的样式? */
</script>
</head>
<body>
<div id='box' style='width: 300px; background-color: red' class='box1'></div>
</body>
</html>
问题1:上面这段代码中为什么设置的.box1{height: 600px;}高度无法显示?
问题2:
alert(oDiv.currentStyle['height'])
alert(getComputedStyle(oDiv)["height"])
我同时alert上面这两段代码的时候为什么在谷歌浏览器上显示不出来?只有当我把alert(oDiv.currentStyle['height'])注释掉下面的alert(getComputedStyle(oDiv)["height"])才能显示?
1、#box{background-color: black;};后面多了个分号,
2、currentStyle只有 IE 和 Opera 支持使用 currentStyle获取 HTMLElement的计算后的样式,其他浏览器中不支持。
3、
var oDiv = document.getElementById("box");
var currentStyle = '';
if(oDiv.currentStyle){
currentStyle = oDiv.currentStyle.height;
}else{
currentStyle = window.getComputedStyle(oDiv).height;
}
alert(currentStyle)
#box{background-color: black;}; 不应该 有 ;
JavaScript之CurrentStyle与getComputeStyle区别与兼容性
https://blog.csdn.net/weixin_42210229/article/details/81101592
另外,.box1{height: 600px;}高度无法显示原因,是因为
#box{background-color: black;};
black;};后面多了一个;分号