JS获取CSS样式属性失败求助:alert未输出预期值
问题原因与解决方案
嘿,我明白你遇到的问题了!你用document.getElementById("kreis").style去获取样式,但弹窗没输出预期值,核心原因是:
element.style这个属性只能获取元素的内联样式(也就是直接写在HTML元素的style属性里的样式,比如<div style="background:red"></div>这种),而你的样式是定义在<style>标签里的内部样式表,所以用.style根本拿不到这些值。
解决办法
你可以用window.getComputedStyle()方法,它能获取元素最终渲染后的所有计算样式,不管样式是来自内联、内部还是外部样式表。
修改后的代码示例
<style> #kreis{ width:200px; height: 200px; border-radius:50%; background:#00FF00; top: 300px; text-align:center; display: inline-block; cursor:pointer; } </style> <div onclick="Ball()" id="kreis"></div> <script> function Ball() { alert("Hola"); // 获取目标元素 const element = document.getElementById("kreis"); // 获取元素的最终计算样式 const computedStyle = window.getComputedStyle(element); // 输出计算后的样式集合对象 alert(computedStyle); // 获取背景色(注意这里返回的是rgb格式值,比如rgb(0, 255, 0)) alert(computedStyle.backgroundColor); // 获取高度 const height = computedStyle.height; alert(height); } </script>
另外提个小细节:你原来的<script>标签没有闭合,我已经在修改后的代码里补上了,这也可能导致一些意外的代码执行问题哦。
如果非要用.style的话,你可以把样式直接写在元素的style属性里,比如:
<div onclick="Ball()" id="kreis" style="width:200px; height:200px; border-radius:50%; background:#00FF00; top:300px; text-align:center; display:inline-block; cursor:pointer;"></div>
但这种方式不利于样式的统一维护,所以更推荐用getComputedStyle()的方案。
内容的提问来源于stack exchange,提问作者Armando Andres Flores
相关产品推荐
相关产品推荐

