JS feature detection to detect the usage of -webkit-calc over calc

微信扫一扫,分享到朋友圈

JS feature detection to detect the usage of -webkit-calc over calc

So I’m quite aware that in general, one should use feature detection in JS vs. browser detection. A good example of this being pushed is jQuery 1.9
‘s drop of $.browser
.

In addition, in every article I read, it says to never use browser detection.

But I have a condition where I need to dynamically calculate the #
of "slots"
available in a JS layout, and it’s being done through calc(100%/{0})
, where {0}
is the #
of slots available.

Of course, in iPad, the .css("height", "calc(100%/3)")
will fail, as it must be prefixed with -webkit-
.

So, can anyone tell me how exactly I should use feature detection (instead of the old $.browser.webkit
) to detect that it requires this?

Problem courtesy of: automaton

Solution

Create a dummy element, insert it in the document, use .cssText.height = 'calc(100px - 50px);'
, and check if the element has the expected height. Repeat this for every vendor-prefix.

Side note: For this kind of questions, you should look in the source code of Modernizr. Others have usually contributed such feature detection scripts, such as
calc.js

.

Modernizr detects whether the feature is present, it doesn’t tell which prefix has to be used. The code below shows how to get the correct prefix:

var calc = (function(){
    var dummy = document.createElement('div');
    var props = ['calc', '-webkit-calc', '-moz-calc', '-o-calc'];
    for (var i=0; i<props.length; ++i) {
        var prop = props[i];
        dummy.style.cssText = 'width:' + prop + '(1px);';
        if (dummy.style.length)
            return prop;
    }
})();

// Usage example:
$('selector').css('height', calc + '(100% / 3)');

(I did not add the -ms-
prefix, because IE started supporting it without the prefix – see http://caniuse.com/calc
.)

Solution courtesy of: Rob W

微信扫一扫,分享到朋友圈

JS feature detection to detect the usage of -webkit-calc over calc

Book Review: Scientific Advertising AKA Original Growth Bible

上一篇

Changing the navigation bar color on the Edit Plus section screen

下一篇

你也可能喜欢

JS feature detection to detect the usage of -webkit-calc over calc

长按储存图像,分享给朋友