我不知道为什么这个代码不能工作!为什么显示警报空白?
<html lang="en">
<head>
<title>Document</title>
<style>
#dd{
height: 300px;
width: 300px;
background-color: mediumblue;
color: white;
}
</style>
</head>
<body>
<label>Color </label><input id="in1" type="text">
<hr>
<div id="dd">
</div>
<script>
var colorTextBox = document.getElementById("in1");
var div = document.getElementById("dd");
div.onclick = function(){
colorTextBox.value = div.style.backgroundColor;
alert(div.style.backgroundColor);
}
</script>
</body>
</html>
当点击div时,div的背景颜色应该写在输入框中,并且也显示在警报中。
有了这个,它就会计算rgb颜色:`
var colorTextBox = document.getElementById("in1");
var div = document.getElementById("dd");
div.onclick = function(){
//colorTextBox.value = div.style.backgroundColor;
//alert(div.style.backgroundColor);
const element = document.querySelector('#dd');
const style = getComputedStyle(element)
var color= style.backgroundColor;
alert(color);
}
<html lang="en">
<head>
<title>Document</title>
<style>
#dd{
height: 300px;
width: 300px;
background-color: mediumblue;
color: white;
}
</style>
</head>
<body>
<label>Color </label><input id="in1" type="text">
<hr>
<div id="dd">
</div>
<script>
</script>
</body>
</html>
element.style.
只能在内联的情况下检索样式。
例如,如果将div更改为 要获得style标记中定义的background-color,应该使用 演示div.style.backgroundcolor
将返回mediumblue
。getComputedStyle(Element)
。GetComputedStyle(div).BackgroundColor
起作用,返回rgb(0,0,205)
,这是MediumBlue的rgb值。