Two methods for determining the CSS browser type prefix using JavaScript: javascriptcss
No matter how annoying we hate browser type prefixes, we have to face them every day. Otherwise, something cannot work normally. These prefixes are used in two ways: in CSS (for example, "-moz-") and in JS. There is a magical X-Tag project with a very clever JavaScript script that can be used to determine what prefix is currently used-let me show how it works!
For example, the CSS prefix, IE is "-ms-", the Old Opera version is "-o-", and Firefox is "-moz -", safari/Chrome is "-webkit -". JavaScript has multiple ways to judge them.
Method 1: feature Determination
// Obtain the CSS prefix of the browser var prefix = function () {var div = document. createElement ('div '); var cssText ='-webkit-transition: all. 1 s;-moz-transition: all. 1 s;-o-transition: all. 1 s;-ms-transition: all. 1 s; transition: all. 1 s; '; div.style.css Text = cssText; var style = div. style; if (style. webkitTransition) {return '-webkit-';} if (style. upload transition) {return '-moz-';} if (style. oTransition) {return '-o-';} if (style. msTransition) {return '-ms-';} return '';}();
Create a div, add the css style prefix-webkit-,-moz-,-o-, and-ms-to it, and obtain the style. xxxTransition determines the prefix.
Method 2: getComputedStyle: retrieve all the styles of documentElement and parse them.
Obtain styles through window. getComputedStyle and convert styles into an array.
var styles = window.getComputedStyle(document.documentElement, '');var arr = [].slice.call(styles);console.log(arr);
Firefox arr is as follows:
Chrome arr is as follows:
We can see that the CSS prefix name has its own browser implementation.
Concatenate all attributes into a string, and then use a regular expression to match the prefix.
// Get the CSS prefix of the browser var prefix = function () {var styles = compile into getcomputedstyle(document.doc umentElement, ''); var core = (Array. prototype. slice. call (styles ). join (''). match (/-(moz | webkit | MS)-/) | (styles. OLink = ''& ['', 'O']) [1]; return '-' + core + '-';}();
We can see that method 2 is much less code than method 1. Methods 1 and 2 use anonymous functions to return results after one-time execution. You do not need to call the function every time you make a decision.
The above content is a small series of two methods to introduce you to use JavaScript to determine the CSS browser type prefix, I hope you like it.