I searched for a way to detect whether a browser supports CSS calc and found this: How can I check if CSS calc() is available using JavaScript? I modified the solution of No. 5 as follows:
我搜索了一种方法来检测浏览器是否支持CSS calc,然后发现:如何使用JavaScript检查CSS calc()是否可用?我对5号溶液做了如下修改:
help = $('<img src="/images/buttonup.png">')
help.css({ width: "10px" });
help.css({ width: "calc(10px + 10px)" });
if (help.width() == 20) var calcSupport = true; else var calcSupport = false;
Unfortunately this doesn't work in Chrome: help.width() returns 0 although Chrome supports calc obviously. In Firefox it works fine. What am I doing wrong?
不幸的是,这在Chrome中是行不通的:help.width()返回0,尽管Chrome明显支持calc。在Firefox中运行良好。我做错了什么?
3 个解决方案
#1
3
Chrome can't reliably provide computed styles of an element which hasn't been added to the DOM.
Chrome不能可靠地提供未添加到DOM的元素的计算样式。
So you can append the element to the body
, read its width, and remove it.
因此,您可以将元素附加到主体,读取它的宽度,并删除它。
var el = document.createElement('img');
el.style.width = "calc(10px + 10px)";
document.body.appendChild(el);
var calcSupport = getComputedStyle(el).width == '20px';
document.body.removeChild(el);
For really old browsers that don't support getComputedStyle
, you can use jQuery $(el).width() == 20
.
对于不支持getComputedStyle的老浏览器,可以使用jQuery $(el).width() == 20。
#2
1
I think so this is what you are looking for..
我想这就是你要找的。
HTML:
HTML:
<img src="http://davidwalsh.name/demo/css3logo250.jpg" class='img'>
CSS:
CSS:
.img{
width: 100px;
width: -webkit-calc(10px + 10px);
width: -moz-calc(10px + 10px);
width: -o-calc(10px + 10px);
}
Javascript:
Javascript:
var help = $(".img");
if(help.width() == 20){
var calcSupport = true;
alert('calc() is supported');
}else{
var calcSupport = false;
}
JSFiddle
#3
0
Better use CSS.supports
:
更好地利用CSS.supports:
var calcSupport = CSS.supports("width", "calc(10px + 10px)");
#1
3
Chrome can't reliably provide computed styles of an element which hasn't been added to the DOM.
Chrome不能可靠地提供未添加到DOM的元素的计算样式。
So you can append the element to the body
, read its width, and remove it.
因此,您可以将元素附加到主体,读取它的宽度,并删除它。
var el = document.createElement('img');
el.style.width = "calc(10px + 10px)";
document.body.appendChild(el);
var calcSupport = getComputedStyle(el).width == '20px';
document.body.removeChild(el);
For really old browsers that don't support getComputedStyle
, you can use jQuery $(el).width() == 20
.
对于不支持getComputedStyle的老浏览器,可以使用jQuery $(el).width() == 20。
#2
1
I think so this is what you are looking for..
我想这就是你要找的。
HTML:
HTML:
<img src="http://davidwalsh.name/demo/css3logo250.jpg" class='img'>
CSS:
CSS:
.img{
width: 100px;
width: -webkit-calc(10px + 10px);
width: -moz-calc(10px + 10px);
width: -o-calc(10px + 10px);
}
Javascript:
Javascript:
var help = $(".img");
if(help.width() == 20){
var calcSupport = true;
alert('calc() is supported');
}else{
var calcSupport = false;
}
JSFiddle
#3
0
Better use CSS.supports
:
更好地利用CSS.supports:
var calcSupport = CSS.supports("width", "calc(10px + 10px)");