I'd like to use width: calc(100% -100px);
which does the job perfectly for what I need it for, the only problem is its compatibility. At the moment it only works in the latest browsers and not at all in Safari.
Could I make an alternative using jQuery? ie. get the 100% width of an object -100px and then dynamically set the result as the CSS width (so it would be responsive)
If you have a browser that doesn't support the calc
expression, it's not hard to mimic with jQuery:
$('#yourEl').css('width', '100%').css('width', '-=100px');
It's much easier to let jQuery handle the relative calculation than doing it yourself.
I think this may be another way
var width= $('#elm').width();
$('#element').css({ 'width': 'calc(100% - ' + width+ 'px)' });
100%-100px is the same
div.thediv {
width: auto;
margin-right:100px;
}
With jQuery:
$(window).resize(function(){
$('.thediv').each(function(){
$(this).css('width', $(this).parent().width()-100);
})
});
Similar way is to use jQuery resize plugin
试试jQuery animate()
方法,例如。
$("#divid").animate({'width':perc+'%'});
Its not that hard to replicate in javascript :-) , though it will only work for width and height the best but you can expand it as per your expectations :-)
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));
}
If you want to use calc in your CSS file use a polyfill like PolyCalc . Should be light enough to work on mobile browsers (eg below iOS 6 and below Android 4.4 phones).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.