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

前端 未结 6 703
傲寒
傲寒 2020-11-28 12:11

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:

         


        
6条回答
  •  感动是毒
    2020-11-28 12:56

    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/

提交回复
热议问题