还有一个基本的问题,我似乎在网上找不到答案。我可以使用javascript轻松地更改元素的CSS属性,
document.getElementById("ExampleID").style.height="30px";但是,每当我尝试将属性打印到控制台时,
console.log(document.getElementById("ExampleID").style.height);它打印空行而不是属性。如何打印所需元素的样式属性值?非常感谢
发布于 2018-08-01 17:27:33
在这种情况下,您需要检查HTML部件。
window.getComputedStyle()
window.getComputedStyle()方法返回一个对象,该对象在应用活动样式表并解决这些值可能包含的任何基本计算之后,报告元素的所有CSS属性的值。单个CSS属性值是通过对象提供的API访问的,或者是通过使用CSS属性名称进行索引来访问的。下面是工作片段:
var divEle=document.getElementById("ExampleID");
console.log("Before:height::"+divEle.style.height);
console.log("Before:color::"+divEle.style.color);
var heightCss = window.getComputedStyle(divEle, null).getPropertyValue("height");
var colorCss = window.getComputedStyle(divEle, null).getPropertyValue("color");
console.log("Before:height from css::"+heightCss)
console.log("Before:color from css::"+colorCss)
function changeCss(){
divEle.style.height="30px";
divEle.style.color="blue";
console.log("After:height::"+divEle.style.height);
console.log("After:color::"+divEle.style.color);
}.divClass {
height: 40px;
color: red;
width: 40px;
border: 2px solid black;
}<div class="divClass" id="ExampleID">test</div><div><input type="button" onClick="changeCss();" value="Change Css"/></div>
https://stackoverflow.com/questions/51638974
复制相似问题