Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

Can I fetch the value of a non-standard CSS property via Javascript?

I am trying to read a custom (non-standard) CSS property, set in a stylesheet (not the inline style attribute) and get its value. Take this CSS for example:

#someElement {
  foo: 'bar';
}

I have managed to get its value with the currentStyle property in IE7:

var element = document.getElementById('someElement');
var val = element.currentStyle.foo;

But currentStyle is MS-specific. So I tried getComputedStyle() in Firefox 3 and Safari 3:

var val = getComputedStyle(element,null).foo;

...and it returns undefined. Does anyone know a cross-browser way of retreiving a custom CSS property value?

(As you might have noticed, this isn't valid CSS. But it should work as long as the value follows the correct syntax. A better property name would be "-myNameSpace-foo" or something.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Modern browsers will just throw away any invalid css. However, you can use the content property since it only has effect with :after, :before etc. You can store JSON inside it:

#someElement {
    content: '{"foo": "bar"}';
}

Then use code like this to retrieve it:

var CSSMetaData = function() {

    function trimQuotes( str ) {
         return str.replace( /^['"]/, "" ).replace( /["']$/, "" );   
    }

    function fixFirefoxEscape( str ) {
        return str.replace( /"/g, '"' );
    }

    var forEach = [].forEach,
        div = document.createElement("div"),
        matchesSelector = div.webkitMatchesSelector ||
                          div.mozMatchesSelector ||
                          div.msMatchesSelector ||
                          div.oMatchesSelector ||
                          div.matchesSelector,
        data = {};

    forEach.call( document.styleSheets, function( styleSheet ) {
        forEach.call( styleSheet.cssRules, function( rule ) {
            var content = rule.style.getPropertyValue( "content" ),
                obj;

            if( content ) {
                content = trimQuotes(content);
                try {
                   obj = JSON.parse( content );
                }
                catch(e) {
                    try {

                        obj = JSON.parse( fixFirefoxEscape( content ) );
                    }
                    catch(e2) {
                        return ;
                    }

                }
                data[rule.selectorText] = obj;
            }
        });

    });


    return {

        getDataByElement: function( elem ) {
            var storedData;
            for( var selector in data ) {
                if( matchesSelector.call( elem, selector ) ) {
                    storedData = data[selector];
                    if( storedData ) return storedData;

                }
            }

            return null;
        }
    };

}();
var obj = CSSMetaData.getDataByElement( document.getElementById("someElement"));
console.log( obj.foo ); //bar

Note, this is only for modern browsers. Demo: http://jsfiddle.net/xFjZp/3/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...