Home>

No matter how fast the browser updates,It claims to support standards.Different manufacturers,There are still many differences between them.We need to distinguish these differences,Do different processing for different browsers.

No matter how much we hate browser type prefixes,We all have to face it every day,No, something doesn't work.These prefixes are used in two ways:in css (eg "-moz-") and in js. There is a magical x-tag project with a 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 is ​​"-ms-" for ie, "-o-" for old opera, "-moz-" for firefox, and "-webkit-" for safari/chrome. JavaScript has several ways to judge them.

Method 1:Characteristic Judgment

//take the browser's css prefix
var prefix=function () {
  var div=document.createelement ("div");
  var csstext="-webkit-transition:all .1s;-moz-transition:all .1s;-o-transition:all .1s;-ms-transition:all .1s;transition:all .1s;";
  div.style.csstext=csstext;
  var style=div.style;
  if (style.webkittransition) {
    return "-webkit-";
  }
  if (style.moztransition) {
    return "-moz-";
  }
  if (style.otransition) {
    return "-o-";
  }
  if (style.mstransition) {
    return "-ms-";
  }
  return "";
} ();

Create a div, add -webkit-, -moz-, -o-, -ms- to the css style, and then obtain the style. Use style.xxxtransition to determine which prefix.

Method 2:getcomputedstyle gets all styles of documentelement and then parses

First get styles through window.getcomputedstyle and convert styles into an array

var styles=window.getcomputedstyle (document.documentelement, "");
var arr=[] .slice.call (styles);
console.log (arr);
</pre>
</div>
<p>
firefox arr is as follows
</p>
<p>
chrome arr is as follows
</p>
<p>
You can see that the css prefix name has been implemented by the respective browser itself.
</p>
<p>
Concatenate all attributes into a string,Then use regular expressions to find the prefix.
</p>
<div>
<pre>
//take the browser's css prefix
var prefix=function () {
  var styles=window.getcomputedstyle (document.documentelement, "");
  var core=(
    array.prototype.slice
    .call (styles)
    .join ("")
    .match (/-(moz | webkit | ms)-/) || (styles.olink === "" && ["", "o"])
  )[1];
  return "-" + core + "-";
} ();

We see that Method 2 has significantly less code than Method 1.Both method 1 and method 2 use anonymous functions to return results after one-time execution.You don't need to call the function every time you judge.

The above is how we use javascript to determine the CSS browser type prefix through two methods.Hope you like it.

  • Previous C # method to modify the IIS site framework version number
  • Next C # method for obtaining the serial number of a USB flash drive