$(function () {
var scrollTop = 0, //缓存上一次触发scroll的时候的scrollTop值
appendIndex = 0, //由于第23行append这个操作需要时间,在这个时间内可能多次触发scroll事件,为了不会append多次,这里缓存一个appendIndex变量,标识是否已经进行append操作
removeIndex = 0, //同上,为了第46行不会detach多次
firstTitle = $("p.contentTitle").eq(0);
if (firstTitle != undefined) {
$("#topTitle p.titleNormal").html(firstTitle.html());
}
$(window).scroll(function () {
var topTitle = $("#topTitle p"), //顶部title
topTitleWrap = $("#topTitle"), //顶部title的容器
curIndex = parseInt(topTitle.last().attr("data-index")), //顶部title最后的索引值
nextTitle = $("p.contentTitle").eq(curIndex + 1), //向上滑动时下一个title
prevTitle = $("p.contentTitle").eq(curIndex - 1), //向下滑动时上一个title
curTitle = $("p.contentTitle").eq(curIndex),
curScrollTop = $("body").scrollTop(); //取得当前scrollTop的值 if (curScrollTop > scrollTop) {//如果向上滑动
if (nextTitle[0] != undefined) {
if (nextTitle[0].getBoundingClientRect().top <= 52) {//如果下一个title与顶部的title贴到一起或者超过它
var nextTitleIndex = parseInt(nextTitle.attr("data-i")) - 1; //下一个title的索引值
var lastTitleIndex = parseInt(topTitle.last().attr("data-index")); //顶部最后一个title的索引值
if (nextTitleIndex == lastTitleIndex + 1) {
if (appendIndex == lastTitleIndex) {
topTitleWrap.html("<p class='titleNormal' data-index=" + nextTitleIndex + ">" + nextTitle.html() + "</p>");
}
removeIndex = nextTitleIndex;
appendIndex = nextTitleIndex;
}
}
}
}
else {//如果向下滑动
if (prevTitle[0] != undefined && curTitle[0] != undefined) {
if (curTitle[0].getBoundingClientRect().top >= 0) {
var prevTitleIndex = parseInt(curTitle.attr("data-i")) - 1;
var lastTitleIndex = parseInt(topTitle.last().attr("data-index"));
if (prevTitleIndex == lastTitleIndex) {
if (removeIndex == lastTitleIndex && removeIndex != 0) {
topTitleWrap.html("<p class='titleNormal' data-index=" + parseInt(curIndex - 1) + ">" + prevTitle.html() + "</p>");
}
if (curTitle.attr("data-i") - 1 > 0) {
appendIndex = prevTitleIndex - 1;
removeIndex = prevTitleIndex - 1;
}
}
}
}
}
scrollTop = curScrollTop;
});
});