我想使用width: calc(100% -100px);
,它完美地完成了我需要的工作,唯一的问题是它的兼容性。目前它只能在最新的浏览器中工作,在Safari中根本无法工作。
我是否可以使用jQuery来创建一个替代方案?例如:获取对象的100%宽度-100px,并将结果动态设置为CSS宽度(这样它就具有响应性)
如果你的浏览器不支持calc
表达式,使用jQuery模拟并不难:
$('#yourEl').css('width', '100%').css('width', '-=100px');
让jQuery处理相对计算比自己处理要容易得多。
$(window).resize(function() { /* 把 jQuery 计算代码放在这里 */ });
,这样它就会在窗口大小改变时自动计算宽度。 - Dexter Huinda#yourEl
的宽度不会改变,它是恒定的。 - Shafizadeh-= 100px
是不起作用的,必须是 -=100px
。 - Gavin我觉得这可能是另一种方式
var width= $('#elm').width();
$('#element').css({ 'width': 'calc(100% - ' + width+ 'px)' });
100%-100px是相同的
div.thediv {
width: auto;
margin-right:100px;
}
使用jQuery:
$(window).resize(function(){
$('.thediv').each(function(){
$(this).css('width', $(this).parent().width()-100);
})
});
类似的方法是使用jQuery调整大小插件
position:absolute; top:0; left:0;
,那么上面的示例是否有效? - sam
- samwidth:90%; margin-right:-100px;
,它会起作用吗? - samanimate()
方法,例如:$("#divid").animate({'width':perc+'%'});
$('#button-sidebar').animate({width: calc(50% + 20px)},400);
- bhoward'width', '100%'
和'width', '-=100px'
,它会实现你想要的效果。 - Nick Felker虽然它只适用于宽度和高度,但在JavaScript中复制并不难 :-) ,您可以根据期望进行扩展 :-)
function calcShim(element,property,expression){
var calculated = 0;
var freed_expression = expression.replace(/ /gi,'').replace("(","").replace(")","");
// Remove all the ( ) and spaces
// Now find the parts
var parts = freed_expression.split(/[\*+-\/]/gi);
var units = {
'px':function(quantity){
var part = 0;
part = parseFloat(quantity,10);
return part;
},
'%':function(quantity){
var part = 0,
parentQuantity = parseFloat(element.parent().css(property));
part = parentQuantity * ((parseFloat(quantity,10))/100);
return part;
} // you can always add more units here.
}
for( var i = 0; i < parts.length; i++ ){
for( var unit in units ){
if( parts[i].indexOf(unit) != -1 ){
// replace the expression by calculated part.
expression = expression.replace(parts[i],units[unit](parts[i]));
break;
}
}
}
// And now compute it. though eval is evil but in some cases its a good friend.
// Though i wish there was math. calc
element.css(property,eval(expression));
}