How to get a list of valid values ​​for a CSS property with javascript?

Is there a way to get a list of valid values ​​for a given CSS property with Javascript, or check if the value you really set is valid?

Example. If I try to set document.getElementById('foo').style.cursor = "grab"; .

Nothing happens, and the property remains unchanged (at least in chrome).

I would like to get a list of valid values ​​only for the current browser.

For example, in Firefox, I would get -moz-grab in the list, and in IE, I would not get capture or any of its variants.

I want to be able to add provider prefixes if necessary, and possibly have a way to provide a backup.

+5
source share
2 answers

I know that your question asks for a way to validate provider-specific cursors (and possibly other CSS properties), but if all you are looking for is a cross-browser solution for cursor styles, you can just want to use your own images for the cursors in question.

http://www.google.com/intl/en_ALL/mapfiles/closedhand.cur http://www.google.com/intl/en_ALL/mapfiles/openhand.cur

For example, you can use:

 document.getElementById('foo').style.cursor = "url(/closedhand.cur) 4 4"; 

You might want to use this in conjunction with validation to ensure that known properties are valid, for example:

 if( window.CSS.supports('cursor','grab') ) { cursor = 'grab'; } else if( window.CSS.supports('cursor', '-moz-grab') ) { cursor = '-moz-grab'; } else { cursor = 'url(/grab.cur)'; } document.getElementById('foo').style.cursor = cursor; 

You can easily expand this to check all the popular provider prefixes, and then apply this logic only to properties with which you know they have limited browser support.

CSS.supports API Browser Compatibility
CSS.supports MDN

+2
source

One approach that comes to my mind is to pre-populate the arrays with actual css values, and then do a search -

 var validValues = { 'textAlign': ['left', 'right', 'center', 'justify', 'start'] }; var userSpecifiedCSSValue = documet.getElementById('foo').style.textAlign.toLower(); if (validValues.textAlign.indexOf(userSpecifiedCSSValue) > -1) { // valid } 

Note: indexOf not available for IE <= 8.

If you want to make it shared -

 var userStyle = document.getElementById('foo').style, userSpecifiedValue, allowedCSSValues; for (cssProperty in userStyle) { if (userStyle.hasOwnProperty(cssProperty) && validValues.hasOwnProperty(cssProperty)) { userSpecifiedValue = userStyle[cssProperty].toLower(); allowedCSSValues = validValues[cssProperty] if (allowedCSSValues.indexOf(userSpecifiedValue) > -1) { // valid } else { // invalid } } } 

If you also want to enable browser-specific validation, you can create a list of valid values ​​based on your browser type. Just create another layer in the object -

 var validValues = { 'chrome': { 'textAlign': []// arrays with values } } 

However, for me it still looks like a hacker solution.

+1
source

All Articles