1

目标是在外部样式表中定义自定义 CSS 属性值。

摆弄它

外部 CSS:

#myDiv {
  --myCustomProperty: 'myCustomValue';
}

标记:

<html>
    <div id='myDiv'></div>
</html>

CSS 规范中没有任何内容说自定义属性无效。但是,浏览器会将它们呈现为无效,但理论上它们应该仍然可以通过 window.getComputedStyle 或类似方式使用。Firebug 在样式窗格中显示自定义属性及其值,但将其标记为已覆盖。

以下片段来自:http ://www.quirksmode.org/dom/getstyles.html

JavaScript:

function getStyle(el,styleProp) {
    var x = document.getElementById(el);
    if (x.currentStyle)
      var y = x.currentStyle[styleProp];
    else if (window.getComputedStyle)
      var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
      return y;
}

var value = getStyle('myDiv', '--myCustomProperty');

alert(value);

输出应该是字符串“myCustomValue”

4

2 回答 2

0

这应该可以工作(在 Firefox 32 中测试)。

    <html>
<head>

<style>
#myDiv {
  --myCustomProperty: 'myCustomValue';
}
</style>
</head>
<body>
<div id='myDiv'></div>
<script>
function getStyle(el,styleProp) {
    var x = document.getElementById(el);
    if (x.currentStyle)
      var y = x.currentStyle[styleProp];
    else if (window.getComputedStyle)
      var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
      return y;
}

var value = getStyle('myDiv', '--myCustomProperty');

alert(value);
</script>
</body>
</html>

http://jsfiddle.net/tugvgs1z/1/ 但是,这在 Chrome 和 IE 11 中不起作用。关于 CSS custom-property API on link有很好的讨论。

于 2014-10-23T04:44:42.293 回答
0

如前所述,也许这会对您有所帮助:

您可以将元素的自定义属性存储在一个 .json 文件中,供人们编辑。

结构可能类似于:

{
    "element": 'myDiv',
    "properties": [
            {
                "propertyName": 'SomeName',
                "propertyValue" : 'SomeValue'
            },
            {
                "propertyName" : 'SomeOtherName',
                "propertyValue"  : 'SomeOtherValue'
            },

        ]

    }

然后,您需要编写一个 javascript 函数来查找具有任何给定元素的属性的正确值。这至少适用于所有浏览器。

可以在此处找到搜索 json 对象的示例: 使用 JQuery 搜索 JSON 对象

您可以使用以下方法将 json 文件加载到变量中: Loading local JSON file

它可能仍然不是一个理想的解决方案,但它可以跨浏览器工作。

于 2014-10-23T05:19:29.700 回答