当div的2/3在viewport中时jQuery触发
我需要在单页网站上更改“活动”菜单项,当用户向下滑动或向上滑动时,可以在视口中看到类似三分之二的div。 我发现了一些jQuery插件,但所有这些都是当整个div被查看。
简单地说,我需要像在这个网页上一样: https://vivaldi.com/
: https://vivaldi.com/
而我的页面将如下所示: http : //jsfiddle.net/kwbddvau/2/
html{height:calc(100% - 100px) !important;width:100% !important; margin:0px; padding:0px;} body{height:500% !important;width:100% !important; margin:0px; padding:0px;} .page {height:20% !important; width:100% !important;} #page1{background-color:red; margin-top: 100px;} #page3{background-color:green;} #page5{background-color:blue;} #menu{width: 100%; height: 100px; color: #fff; background-color: black; position: fixed; top:0px} #menu a {color: white; text-decoration:none;} #menu a.active {color: red; text-decoration:underline;}
<div id="menu"><div id="menu"><a href="#page1" class="active">Home</a> | <a href="#page2">Page 2</a> | <a href="#page3">Page 3</a> | <a href="#page4">Page 4</a> | <a href="#page5">Page 5</a></div> </div> <div id="page1" class="page"> page1 </div> <div id="page2" class="page"> page2 </div> <div id="page3" class="page"> page3 </div> <div id="page4" class="page"> page4 </div> <div id="page5" class="page"> page5 </div>
尝试
var page = $(".page") , menu = $("#menu"); $(window).on("scroll", function (e) { var res = $.grep(page, function (el) { return el.getBoundingClientRect().top <= 180 && (el.getBoundingClientRect().bottom >= 180) }); var id = res.slice(-1)[0].id; menu.find("." + id) .addClass("active") .siblings() .removeClass("active") }).scroll();
jsfiddle http://jsfiddle.net/kwbddvau/8/
var page = $(".page") , menu = $("#menu"); $(window).on("scroll", function (e) { var res = $.grep(page, function (el) { return el.getBoundingClientRect().top <= 180 && (el.getBoundingClientRect().bottom >= 180) }); var id = res.slice(-1)[0].id; menu.find("." + id) .addClass("active") .siblings() .removeClass("active") }).scroll();
html { height:calc(100% - 100px) !important; width:100% !important; margin:0px; padding:0px; } body { height:500% !important; width:100% !important; margin:0px; padding:0px; } .page { height:20% !important; width:100% !important; } #page1 { background-color:red; margin-top: 100px; } #page3 { background-color:green; } #page5 { background-color:blue; } #menu { width: 100%; height: 100px; color: #fff; background-color: black; position: fixed; top:0px } .active { border-bottom:2px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div id="menu"> <span class="page1">MENU</span> <span class="page2">MENU</span> <span class="page3">MENU</span> <span class="page4">MENU</span> <span class="page5">MENU</span> </div> <div id="page1" class="page">page1</div> <div id="page2" class="page">page2</div> <div id="page3" class="page">page3</div> <div id="page4" class="page">page4</div> <div id="page5" class="page">page5</div>