css width: calc(100% -100px); alternative using jquery

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

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)

回答1:

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.



回答2:

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



回答3:

I think this may be another way

    var width=  $('#elm').width();      $('#element').css({ 'width': 'calc(100% - ' + width+ 'px)' }); 


回答4:

Try jQuery animate() method, ex.

$("#divid").animate({'width':perc+'%'}); 


回答5:

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 


回答6:

If you want to use calc in your CSS file use a polyfill like PolyCalc. Should be light enough to work on mobile browsers (e.g. below iOS 6 and below Android 4.4 phones).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!