代码之家  ›  专栏  ›  技术社区  ›  Jason Sperske

jQuery.css(“margin top”,value)未在IE8(标准模式)中更新

  •  13
  • Jason Sperske  · 技术社区  · 16 年前

    我正在构建一个绑定到$(window).scroll()事件的自动跟踪div。这是我的JavaScript。

    var alert_top = 0;
    var alert_margin_top = 0;
    
    $(function() {
      alert_top = $("#ActionBox").offset().top;
      alert_margin_top = parseInt($("#ActionBox").css("margin-top"));
    
      $(window).scroll(function () {
        var scroll_top = $(window).scrollTop();
        if(scroll_top > alert_top) {
          $("#ActionBox").css("margin-top", ((scroll_top-alert_top)+(alert_margin_top*2))+"px");
          console.log("Setting margin-top to "+$("#ActionBox").css("margin-top"));
        } else {
          $("#ActionBox").css("margin-top", alert_margin_top+"px");
        };
      });
    });
    

    此代码假定存在此CSS规则

    #ActionBox {
      margin-top: 15px;
    }
    

    现在console.log显示事件在每次应该触发时都在触发,并且它设置了正确的值。但在我的web应用程序的某些页面中,div没有被重绘。这一点特别奇怪,因为在其他页面(IE)中,代码按预期工作(在FF、Opera和WebKit中每次都工作)。所有页面都会评估(根据W3C验证程序和firefoxhtmltidy验证程序,0个错误和0个警告),并且不会抛出JS错误(根据IE开发人员工具栏和Firebug)。另一个谜团是,如果我在IE开发者工具的HTML样式浏览器中取消选择#ActionBox margin top规则,那么div会立即跳回新调整的位置,如果scroll事件触发了重画,那么它应该返回这个位置。另外,如果我强制IE8进入怪癖模式或兼容模式,那么偶数会触发一个更新。

    5 回复  |  直到 16 年前
        1
  •  13
  •   Mottie    16 年前

    demo here .

    • 一种解决方案是添加 position: fixed CSS的定义,但我看这对你不起作用
    • top .
    • 更新了代码以适应为其他人找到的解决方案。

    CSS格式

    #ActionBox {
     position: relative;
     float: right;
    }
    

    var alert_top = 0;
    var alert_margin_top = 0;
    
    $(function() {
      alert_top = $("#ActionBox").offset().top;
      alert_margin_top = parseInt($("#ActionBox").css("margin-top"),10);
    
      $(window).scroll(function () {
        var scroll_top = $(window).scrollTop();
        if (scroll_top > alert_top) {
          $("#ActionBox").css("margin-top", ((scroll_top-alert_top)+(alert_margin_top*2)) + "px");
          console.log("Setting margin-top to " + $("#ActionBox").css("margin-top"));
        } else {
          $("#ActionBox").css("margin-top", alert_margin_top+"px");
        };
      });
    });
    

    同样重要的是在你的基础上加一个基数(在本例中是10) parseInt() ,例如。

    parseInt($("#ActionBox").css("top"),10);
    
        2
  •  1
  •   Cheeso    16 年前

    尝试 marginTop margin-top 例如:

    $("#ActionBox").css("marginTop", foo);
    
        3
  •  1
  •   Jason Sperske    16 年前

    我找到答案了!

    我想承认每个人都在努力寻找更好的方法来解决这个问题,不幸的是,由于一系列更大的限制,我无法选择他们作为“答案”(我投票给他们,因为你值得为他们贡献分数)。

    #ActionBox {
      position: relative;
      float: right;
    }
    

    这是最新的 pastbin

    我不知道为什么添加“float:right”可以让IE8在已经触发的事件上完成重绘,但出于某种原因它确实做到了。

        4
  •  1
  •   RckLN    12 年前

    IE8的正确格式是:

      $("#ActionBox").css({ 'margin-top': '10px' });  
    

        5
  •  1
  •   user2164884 user2164884    10 年前

    试试这个方法

    $("your id or class name").css({ 'margin-top': '18px' });  
    
    推荐文章