Jquery没有响应滚动

时间:2016-11-30 20:34:57

标签: jquery html css

我试图在滚动某个点后将元素更改位置设置为固定,但滚动时没有任何反应。我<script src="stiler/jquery-3.1.1.min.js"></script>引用了<head>中的jquery。滚动时根本没有任何事情发生。在DOM控制台中没有错误消息,没有任何错误消息。

&#13;
&#13;
$(document).ready(function(){
var wrap = $('#header-wrap');

$(window).on('scroll', function(e) {
    
  if (this.scrollTop > 147) {
    wrap.addClass('fix');
  } else {
    wrap.removeClass('fix');
  }
  
});
});
&#13;
body {
  background-color: grey;
  margin: 0;
  min-height: 300vh;
}
#header-wrap {
  top: 0;
  width: 100%;
}
#redline {
  top: 0;
  left: 0;
  width: 100%;
  position: fixed;
  height: 10px;
  background-color: #b30027;
  z-index: 99;
}
#velkommen {
  height: 300px;
  width: 100%;
  background-color: white;
  position: relative;
  top: 10px;
  margin-bottom: -60px;
}
#header {
  position: relative;
  left: 0;
  width: 100%;
  background-color: white;
  height: 60px;
}
.fix #header {
  position: fixed;
  top: 10px;
}
h1 {
  margin: 0;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header id="header-wrap">
  <div id="redline"></div>
  <div id="velkommen"></div>
  <div id="header"> <!--This tag should get class="fix"-->
    <h1>#HEADER</h1>
  </div> </header>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

问题是您使用this错误,需要$(this)

$(document).ready(function(){
var wrap = $('#header-wrap');

$(window).on('scroll', function(e) {

  if ($(this).scrollTop > 147) {
    wrap.addClass('fix');
  } else {
    wrap.removeClass('fix');
  }

});
});

这是一个显示它工作的小提琴:https://jsfiddle.net/5sdahw83/

以下是this$(this) jQuery: What's the difference between '$(this)' and 'this'?

的进一步阅读