检测固定位置JavaScript无法在IE中运行

时间:2012-10-09 13:01:33

标签: javascript html css internet-explorer

我使用YS作为固定位置菜单,在Firefox中工作正常,但在IE中没有工作。

$(function(){                     // this is the shorthand for document.ready
  $(document).scroll(function(){    // this is the scroll event for the document

      scrolltop = $(document).scrollTop();  // by this we get the value of the scrolltop ie how much scroll has been don by user
      if(parseInt(scrolltop) >= 80)         // check if the scroll value is equal to the top of navigation
      { 
          $("#navbar").css({"position":"fixed","top":"0"});       // is yes then make the position fixed to top 0
      }
      else
      {
          $("#navbar").css({"position":"absolute","top":"80px"}); // if no then make the position to absolute and set it to 80
      }
  }
}

解决这个问题的解决方案是什么?

3 个答案:

答案 0 :(得分:1)

你的代码working jsfiddle中缺少')'(在IE7和IE9中测试过)

$(function(){                     // this is the shorthand for document.ready
  $(window).scroll(function(){    // this is the scroll event for the document

      scrolltop = $(window).scrollTop();  // by this we get the value of the scrolltop ie how much scroll has been don by user
      if(parseInt(scrolltop) >= 80)         // check if the scroll value is equal to the top of navigation
      { 
          $("#navbar").css({"position":"fixed","top":"0"});       // is yes then make the position fixed to top 0
      }
      else
      {
          $("#navbar").css({"position":"absolute","top":"80px"}); // if no then make the position to absolute and set it to 80
      }
  }); //here
});//here

答案 1 :(得分:1)

对我而言,问题似乎是IE不会触发.scroll事件。至少,不是在jsfiddle。如果你明确地触发了这个事件,那似乎可以解决问题。 this fiddle was tested in IE8并且它有效。代码:

$(function()
{
    $(document).scroll(function()
    {//add var here, avoid evil globals:
        var scrolltop = $(document).scrollTop();  
        if(parseInt(scrolltop) >= 80)         
        { 
            $("#navbar").css({"position":"fixed","top":"0"});       
        }
        else
        {
            $("#navbar").css({"position":"absolute","top":"80px"});
        }
    });//close properly
    $(document).scroll();//explicit call
});//close this, too

答案 2 :(得分:0)

对于位置修复,您的父元素必须具有此样式

position:relative;

最好的问候