导航
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> ul{ width:100%;height:30px;list-style: none;position: fixed; background-color: #ccc; } ul li{ width: 20%; height: 30px; line-height: 30px; text-align: center; float: left; } </style> </head> <body> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> <div data-index="0" class="x" style="width:100px; height:500px"></div> <div id="div1" class="x" data-index="1" style="width:100%; height:250px; background:red;"> </div> <div id="div2" class="x" data-index="2" style="width:100%; height:100px; background:blue;"> </div> <script type="text/javascript" src="jquery-1.7.2.js"></script> <script type="text/javascript"> // 返回浏览器的可视区域位置 function getClient() { var l, t, w, h; l = document.documentElement.scrollLeft || document.body.scrollLeft; t = document.documentElement.scrollTop || document.body.scrollTop; w = document.documentElement.clientWidth; h = document.documentElement.clientHeight; return { left: l, top: t, width: w, height: h }; } // 返回待加载资源位置 function getSubClient(p) { var l = 0, t = 0, w, h; w = p.offsetWidth; h = p.offsetHeight; while (p.offsetParent) { l += p.offsetLeft; t += p.offsetTop; p = p.offsetParent; } return { left: l, top: t, width: w, height: h }; } // 判断两个矩形是否相交,返回一个布尔值 function intens(rec1, rec2) { var lc1, lc2, tc1, tc2, w1, h1; lc1 = rec1.left + rec1.width / 2; lc2 = rec2.left + rec2.width / 2; tc1 = rec1.top + rec1.height / 2; tc2 = rec2.top + rec2.height / 2; w1 = (rec1.width + rec2.width) / 2; h1 = (rec1.height + rec2.height) / 2; return Math.abs(lc1 - lc2) < w1 && Math.abs(tc1 - tc2) < h1; } $(".x").each(function(){ var index = $(this).attr('data-index'); var rec1 = getClient(); var rec2 = getSubClient($(this)[0]); if(intens(rec1, rec2)){ $("ul li:eq("+index+")").css({ background: '#FF0000' }); $("ul li:eq("+index+")").siblings('li').css({ background: '#ccc' }); } }); window.onscroll = function() { $(".x").each(function(){ var index = $(this).attr('data-index'); var rec1 = getClient(); var rec2 = getSubClient($(this)[0]); if(intens(rec1, rec2)){ $("ul li:eq("+index+")").css({ background: '#FF0000' }); $("ul li:eq("+index+")").siblings('li').css({ background: '#ccc' }); } }); } </script> </body> </html>