将CSS calc()函数转换为jQuery以扩展浏览器支持

时间:2013-05-27 06:18:51

标签: jquery css

我有以下用于solve this problem的代码。它适用于IE9 / Chrome:

    $(document).ready(function () {
        var legendWidth = $('#titleInner').outerWidth();
        var margin = 'calc((100% - ' + legendWidth + 'px) / 2)';
        $('#titleInner').css('margin-left', margin);
        $('#titleInner').css('margin-right', margin);
    });

但是,我想摆脱CSS calc() function,以便在IE7 / 8中运行。

我看过this question/answer使用jQuery进行计算,这似乎是一个很好的解决方案。

问题是我无法获得语法/链接工作。

以下是我的尝试:

    $(document).ready(function () {
        var legendWidth = $('#titleInner').outerWidth();
        $('#titleInner').css('margin-left', '100%').css('margin-left', '-' + legendWidth + 'px').css('margin-left', '/2');
        $('#titleInner').css('margin-right', '100%').css('margin-right', '-' + legendWidth + 'px').css('margin-right', '/2');
    });

我尝试了一些变化(删除'px'等),但没有运气。我也无法弄清楚如何在多个chain elements中添加parens来限定'/ 2'。

那么,任何人都可以帮助使用等同于var margin = 'calc((100% - ' + legendWidth + 'px) / 2)';的jQuery吗?

1 个答案:

答案 0 :(得分:0)

这可能有效:

$(document).ready(function () {
    var legendWidth = $('#titleInner').outerWidth();
    var legendParentWidth = $('#titleInner').parent().outerWidth();
    var margin = (legendParentWidth - legendWidth) / 2;
    $('#titleInner').css('margin-left', margin + 'px');
    $('#titleInner').css('margin-right', margin + 'px');
});

或者链接:

$(document).ready(function () {
    var legendWidth = $('#titleInner').outerWidth();
    $('#titleInner').css('margin-left', '100%').css('margin-left', function(){
        return (($('#titleInner').css('margin-left') - legendWidth) / 2) + 'px';
    });
    $('#titleInner').css('margin-right', '100%').css('margin-right', function(){
        return (($('#titleInner').css('margin-right') - legendWidth) / 2) + 'px';
    });
});
相关问题