【问题标题】:Convert CSS calc() function to jQuery for expanded browser support将 CSS calc() 函数转换为 jQuery 以扩展浏览器支持
【发布时间】:2013-05-21 23:12:34
【问题描述】:

我有以下代码用于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 限定“/2”。

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

【问题讨论】:

    标签: jquery css


    【解决方案1】:

    这可能有效:

    $(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';
        });
    });
    

    【讨论】:

    • 好主意。在 IE9 中工作,但不幸的是在 IE7/8 中不工作。
    • @DavidHAust 快速提问:您使用的是 jQuery 的 2.x 版本吗?
    • 不,1.8.1 版本。你认为这会有所作为吗?
    • 是的,2.x 版本根本无法在 IE6/7/8 上运行...所以如果您使用它,它会解释为什么我的代码无法运行 ;)
    • 您的链接版本也不起作用。强制内容离开页面的右侧。链接是否从左到右进行评估?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 2015-09-23
    • 2011-03-30
    • 2018-02-24
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    相关资源
    最近更新 更多