我有这些元素:
<div class="parent"><div class="child"></div></div>
CSS:
.parent{max-width:100px}
是否可以使用“child”的“parentNode”(父节点的名称不可预测)获取css中指定的“max-width”值,以便与当前变量数据进行比较?
我在尝试:
var childDIV=querySelector('.child');
var result= childDIV.parentNode.style.maxWidth`
“结果”为空。
另一个尝试是使用“getComputedStyle”方法:
var result =window.getComputedStyle(childDIV.parentNode,null);
result.getPropertyValue("maxWidth");
尽管“getComputedStyle”的值中显示了正确的“maxWidth”值,但“result”为空。
var childDIV=document.querySelector('.child');
var result= childDIV.parentNode.style.maxWidth;
console.log(`Approach 1: ${result}`);
var result =window.getComputedStyle(childDIV.parentNode,null);
result = result.getPropertyValue("maxWidth");
console.log(`Approach 2: ${result}`);
.parent{max-width:100px}
<div class="parent"><div class="child"></div></div>
最佳答案
您走在正确的轨道上 - 因此,您的第一种方法在这种情况下不起作用,因为该元素在其样式声明中没有直接包含 max-width
(请参见下面的示例 .other
用于此将 工作的时间)。
第二种方法是正确的,但是你有点混淆了访问参数 - 如果你使用 .getPropertyValue
,你使用 CSS 样式 "max-width"
,并且如果你不这样做,你可以像 .style
那样使用 .maxWidth
:
var childDIV=document.querySelector('.child');
var result= document.querySelector('.other').style.maxWidth;
console.log(`Approach 1: ${result}`);
var compStyle = window.getComputedStyle(childDIV.parentNode,null);
result = compStyle.maxWidth;
console.log(`Approach 2: ${result}`);
result = compStyle.getPropertyValue("max-width");
console.log(`Approach 3: ${result}`);
.parent{max-width:100px}
<div class="parent"><div class="child"></div></div>
<div class="other" style="max-width:50px"></div>
关于javascript - 获取父 javascript 的 CSS 最大宽度值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57531571/