窗口滚动功能超过顶部不正确

时间:2017-04-26 18:25:28

标签: javascript jquery scroll window

我正在运行一个窗口滚动功能,以便在查看div #home-cover1时进行测量。然后当代码不在视图中运行else语句时。

如果你拉起你的控制台,你会发现其他人永远不会在运行,而且无论你在哪个div中,都会看到#home-cover1。{/ p>

有谁知道为什么?

$(function() {
		var section1 = $('#home-cover1');
		if (section1.length) {
			var oTop = section1.offset().top - window.innerHeight;
		}
		$(window).scroll(function() {
			var pTop = $(document).scrollTop();
			if (pTop > oTop) {
				console.log("OVer it");
				$('#proposal-trigger').removeClass('active');
			}
			else {
				console.log("Nope it");
				$('#proposal-trigger').addClass('active');
			}
		});
	});
#home-cover1 {
  background: green;
  height: 100vh;
   width: 100%;
}
#red {
  background: red;
  height: 100vh;
   width: 100%;
}
#blue {
  background: blue;
  height: 100vh;
   width: 100%;
}
#proposal-trigger {
	background: #3B3B3B;
	width: 100px;
	height: 100px;
	position: fixed;
	bottom: 0;
	right: 200px;
	opacity: 0;
	transition: ease 0.3s;-webkit-transition: ease 0.3s;
}
#proposal-trigger.active {
	opacity: 1;
	transition: ease 0.3s;-webkit-transition: ease 0.3s;
}	
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section id="home-cover1"></section>
<section id="red"></section>
<section id="blue"></section>
<div id="proposal-trigger"></div>

1 个答案:

答案 0 :(得分:1)

快速检查后var oTop = section1.offset().top - window.innerHeight;结果为负数,因此pTop始终大于oTop。您必须按section1.offset()减去window.innerHeight。您还必须将pTop > oTop切换为pTop < oTop。这会检查scrollTop是否低于该部分。

&#13;
&#13;
$(function() {
		var section1 = $('#home-cover1');
		if (section1.length) {
			var oTop = window.innerHeight - section1.offset().top;
		}
		$(window).scroll(function() {
			var pTop = $(document).scrollTop();
      console.log(pTop);
      console.log(oTop);
			if (pTop < oTop) {
				console.log("OVer it");
				$('#proposal-trigger').removeClass('active');
			}
			else {
				console.log("Nope it");
				$('#proposal-trigger').addClass('active');
			}
		});
	});
&#13;
#home-cover1 {
  background: green;
  height: 100vh;
   width: 100%;
}
#red {
  background: red;
  height: 100vh;
   width: 100%;
}
#blue {
  background: blue;
  height: 100vh;
   width: 100%;
}
#proposal-trigger {
	background: #3B3B3B;
	width: 100px;
	height: 100px;
	position: fixed;
	bottom: 0;
	right: 200px;
	opacity: 0;
	transition: ease 0.3s;-webkit-transition: ease 0.3s;
}
#proposal-trigger.active {
	opacity: 1;
	transition: ease 0.3s;-webkit-transition: ease 0.3s;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="home-cover1"></section>
<section id="red"></section>
<section id="blue"></section>
<div id="proposal-trigger"></div>
&#13;
&#13;
&#13;