安卓端网页浏览过程中实时更新title的web实现
1 $(function () { 2 var scrollTop = 0, //缓存上一次触发scroll的时候的scrollTop值 3 appendIndex = 0, //由于第23行append这个操作需要时间,在这个时间内可能多次触发scroll事件,为了不会append多次,这里缓存一个appendIndex变量,标识是否已经进行append操作 4 removeIndex = 0, //同上,为了第46行不会detach多次 5 firstTitle = $("p.contentTitle").eq(0); 6 if (firstTitle != undefined) { 7 $("#topTitle p.titleNormal").html(firstTitle.html()); 8 } 9 $(window).scroll(function () { 10 var topTitle = $("#topTitle p"), //顶部title 11 topTitleWrap = $("#topTitle"), //顶部title的容器 12 curIndex = parseInt(topTitle.last().attr("data-index")), //顶部title最后的索引值 13 nextTitle = $("p.contentTitle").eq(curIndex + 1), //向上滑动时下一个title 14 prevTitle = $("p.contentTitle").eq(curIndex - 1), //向下滑动时上一个title 15 curTitle = $("p.contentTitle").eq(curIndex), 16 curScrollTop = $("body").scrollTop(); //取得当前scrollTop的值 17 18 if (curScrollTop > scrollTop) {//如果向上滑动 19 if (nextTitle[0] != undefined) { 20 if (nextTitle[0].getBoundingClientRect().top <= 52) {//如果下一个title与顶部的title贴到一起或者超过它 21 var nextTitleIndex = parseInt(nextTitle.attr("data-i")) - 1; //下一个title的索引值 22 var lastTitleIndex = parseInt(topTitle.last().attr("data-index")); //顶部最后一个title的索引值 23 if (nextTitleIndex == lastTitleIndex + 1) { 24 if (appendIndex == lastTitleIndex) { 25 topTitleWrap.html("<p class='titleNormal' data-index=" + nextTitleIndex + ">" + nextTitle.html() + "</p>"); 26 } 27 removeIndex = nextTitleIndex; 28 appendIndex = nextTitleIndex; 29 } 30 } 31 } 32 } 33 else {//如果向下滑动 34 if (prevTitle[0] != undefined && curTitle[0] != undefined) { 35 if (curTitle[0].getBoundingClientRect().top >= 0) { 36 var prevTitleIndex = parseInt(curTitle.attr("data-i")) - 1; 37 var lastTitleIndex = parseInt(topTitle.last().attr("data-index")); 38 if (prevTitleIndex == lastTitleIndex) { 39 if (removeIndex == lastTitleIndex && removeIndex != 0) { 40 topTitleWrap.html("<p class='titleNormal' data-index=" + parseInt(curIndex - 1) + ">" + prevTitle.html() + "</p>"); 41 } 42 if (curTitle.attr("data-i") - 1 > 0) { 43 appendIndex = prevTitleIndex - 1; 44 removeIndex = prevTitleIndex - 1; 45 } 46 } 47 } 48 } 49 } 50 scrollTop = curScrollTop; 51 }); 52 });