【问题标题】:JQuery variable: how to convert positive height into negative margin?JQuery变量:如何将正高度转换为负边距?
【发布时间】:2013-05-30 05:53:39
【问题描述】:
<script>
    $(document).ready(function () {
        var footerheight = $('#footer').height();
        $('#footer').css('height', footerheight);
        $('#footer').css('marginTop', footerheight);
        $('#nonfooterinner').css('paddingBottom', footerheight);
    });
    $(window).bind("resize", function () {
        var footerheight = $('#footer').height();
        $('#footer').css('height', footerheight);
        $('#footer').css('marginTop', footerheight);
        $('#nonfooterinner').css('paddingBottom', footerheight);
    });
</script>

<body>
    <div id="nonfooterouter">
        <div id="nonfooterinner">
            body
        </div>
    </div>
    <div id="footer">
        xxx
    </div>
</body>

此脚本获取#footer div 的高度,并将其设置为内部主体包装(#nonfooterinner)的底部填充和#footer 的顶部边距。但是,#footer 的上边距必须是该数字的负值。如何将脚本中的变量“footerheight”转换为仅用于 marginTop 值的负数?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    您可以使用parseInt() 将字符串转换为整数。请检查以下代码:

    var footerheight = $("#footer").height();
    var marginTop = parseInt(footerheight) * -1;
    $("#footer").css("marginTop", marginTop + "px");
    

    【讨论】:

      【解决方案2】:

      Example on jsFiddle

      设置为负数

      $('#footer').css('marginTop', - footerheight);
      

      【讨论】:

      • 我不知道你能做到这一点,太棒了。现在的问题是为什么总是只在 IE 中出现错误,而在其他任何地方都没有?
      • @user2441996 IE 是否存在“px”错误。如果你想避免这个问题,请使用parseInt()
      【解决方案3】:
      var footerheight = $('#footer').height();
      
          $('#footer').css('margin-left', footerheight *-1);
      

      【讨论】:

      • 请为您的解决方案添加一些解释,说明它如何解决问题以及提问者做错了什么或遗漏了什么。
      • 这是一个很好的答案 Avinash Saini。它是如何工作的?
      【解决方案4】:
      var footerheight = $('#footer').height();
      footerheight =-Math.abs(footerheight);
      

      【讨论】:

        【解决方案5】:

        将任何值转换为正数,反之亦然:

        var value = -500
        if(value < 0) { 
          value = value*(-1)
        }
        

        或否定:

        var value = 500
        if(value > 0){
          value = value*(-1)
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-23
          • 1970-01-01
          • 2021-03-16
          • 2023-03-29
          • 2011-04-20
          相关资源
          最近更新 更多