Regardless of our position on vendor prefixes, we have to live with them and occasionally use them to make things work. These prefixes can be used in two formats: the CSS format (-moz-
, as in -moz-element
) and the JS format (navigator.mozApps
). The awesome X-Tag project has a clever bit of JavaScript magic that detects those prefixes in the browser environment -- let me show you how it works!
无论我们在供应商前缀上的立场如何,我们都必须与他们共处,并偶尔使用它们来使工作正常。 这些前缀可以两种格式可以使用:在CSS格式( -moz-
,如在-moz-element
)和JS格式( navigator. mozApps
)。 令人敬畏的X-Tag项目具有一些巧妙JavaScript魔术,可以检测浏览器环境中的这些前缀-让我向您展示它的工作原理!
JavaScript (The JavaScript)
The first step is retrieving the HTML element's CSSStyleDeclaration
:
第一步是检索HTML元素的CSSStyleDeclaration
:
var styles = window.getComputedStyle(document.documentElement, ''),
The next step is converting it to an Array
object and searching for a known prefix type, settling on Opera if none is found:
下一步是将其转换为Array
对象并搜索已知的前缀类型,如果未找到,则在Opera上进行设置:
pre = (Array.prototype.slice
.call(styles)
.join('')
.match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o'])
)[1]
With the CSS prefix found, getting the JS-formatted prefix is simple:
找到CSS前缀后,获取JS格式的前缀很简单:
return {
dom: dom,
lowercase: pre,
css: '-' + pre + '-',
js: pre[0].toUpperCase() + pre.substr(1)
}
The returned object provides an object that looks something like:
返回的对象提供了一个类似于以下内容的对象:
Object {dom: "WebKit", lowercase: "webkit", css: "-webkit-", js: "Webkit"}
A complete representation of the vendor prefixing for the host browser. Here's the complete snippet:
主机浏览器的供应商前缀的完整表示。 这是完整的代码段:
var prefix = (function () {
var styles = window.getComputedStyle(document.documentElement, ''),
pre = (Array.prototype.slice
.call(styles)
.join('')
.match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o'])
)[1],
dom = ('WebKit|Moz|MS|O').match(new RegExp('(' + pre + ')', 'i'))[1];
return {
dom: dom,
lowercase: pre,
css: '-' + pre + '-',
js: pre[0].toUpperCase() + pre.substr(1)
};
})();
Grabbing the CSSStyleDeclaration
from the HTML element is a clever move. This method plays off of the fact that there will always be a vendor-prefixed property in the style declaration, which some may dislike, but is going to be effective for a long time to come. What do you think of this method of vendor prefix detection? Share your thoughts!
从HTML元素获取CSSStyleDeclaration
是一个聪明的举动。 该方法是基于以下事实:样式声明中始终会存在一个供应商前缀的属性,有些人可能会不喜欢它,但是这种属性将在很长一段时间内有效。 您如何看待这种供应商前缀检测方法? 分享你的意见!