Ser*_*erg 3 javascript css parent-child
我有这些要素:
<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`
Run Code Online (Sandbox Code Playgroud)
“结果”为空。
另一种尝试是使用“getCompulatedStyle”方法:
var result =window.getComputedStyle(childDIV.parentNode,null);
result.getPropertyValue("maxWidth");
Run Code Online (Sandbox Code Playgroud)
尽管“getComputedStyle”值中显示了正确的“maxWidth”值,但“result”为空。
var childDIV=querySelector('.child');
var result= childDIV.parentNode.style.maxWidth`
Run Code Online (Sandbox Code Playgroud)
var result =window.getComputedStyle(childDIV.parentNode,null);
result.getPropertyValue("maxWidth");
Run Code Online (Sandbox Code Playgroud)
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}`);Run Code Online (Sandbox Code Playgroud)
你走在正确的轨道上 - 所以,你的第一种方法在这种情况下不起作用,因为该元素没有max-width直接在其样式声明中(请参阅下面的示例,.other了解何时可以使用)。
第二种方法是正确的,但是您混淆了访问参数 - 如果您使用.getPropertyValue,则使用 CSS-style "max-width",如果不使用,则使用.maxWidthlike with .style:
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}`);Run Code Online (Sandbox Code Playgroud)
.parent{max-width:100px}Run Code Online (Sandbox Code Playgroud)
<div class="parent"><div class="child"></div></div>
<div class="other" style="max-width:50px"></div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1099 次 |
| 最近记录: |