Css:如何访问元素未使用的值

css: how to access a value that is not used by an element?

本文关键字:元素 未使用 访问 何访问 Css      更新时间:2023-09-26

我有一个div,它的高度来自一个单独样式表中的CSS类。但这个高度有时会在Javascript中改变。我可以直接从样式表中读取CSS高度而不创建新元素吗?

你可以这样做:

 var myDiv = $("#myId"); 
 alert('initial height from css is: ' + myDiv.css("height"));
 myDiv.css("height","50px");
 alert('height modified by js is: ' + myDiv.css("height"));
 // store modified height value
 var height = myDiv.css("height");
 // set height to an invalid value
 myDiv.css("height","");
 alert('height is now retrieved from css again: ' + myDiv.css("height"));
 // restore height value
 myDiv.css("height",height);

我在jsfiddle.net上创建了一个例子,你可以在这里查看它

这是可能的,只要高度变化是由已知原因引起的。

首先,保存当前的内联高度/类名。然后,重置class/height属性。然后,使用window.getComputedStyle方法读取当前高度。最后,恢复class/height属性。让我们假设不需要删除类名,因为高度只需要通过设置内联height属性来改变。然后:

function getCSSheight(elem) {
    var style = window.getComputedStyle(elem, null);
    return style.getPropertyValue("height"); //Returns 222px;
    // Optionally: Use parseFloat to convert the `22px` to `22`.
}

不,你不能从CSS中读取任何属性。

你可以创建一些后端API,允许你直接从JavaScript更改CSS文件,然后你可以在CSS文件中更改height,而不是将style应用于元素