item

侧栏滑动

基本动作是怎么实现的

  • [x] 划定几个锚点(某标签滑到屏幕中间为一个锚点)
1
2
3
4
5
var anchor = [];
for (var i = 0; i < h1.length; i++) {
anchor[i] = (h1[i].offsetTop - clientHeight / 2) || (h1[i].offsetTop - clientHeight / 2);
}
anchor[3] = scrollHeight - 800;
  • [x] 当滚轮滑动,判断条件在一定范围内显示侧栏;滑动到某锚点范围内被选中;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 滚动定位标签变红
window.onscroll = function() {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
//到达某个范围消失
leftMenu.style.display = ((scrollTop >= anchor[0]) && (scrollTop <= anchor[3])) ? "block" : "block";
// 滑动到锚点处变颜色
for (var i = 0; i < leftMenuLi.length - 1; i++) {
leftMenuLi[i].style.color = ((scrollTop >= anchor[i]-1) && (scrollTop < anchor[i + 1]-1)) ? "red" : ""; //-1在锚点处才变色
leftMenuLi[2].style.color = ((scrollTop >= anchor[2]-1) && (scrollTop < scrollHeight)) ? "red" : "";
// console.log("0-->"+scrollHeight)
console.log("1-1111-->" + scrollTop)
console.log("1-2222-->" + anchor[i])
}
}
  • [x] (给侧栏标签循环绑定点击事件)点击标签,以一定速度缓慢滑动到锚点
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 点击标签定位
for (var i = 0; i < leftMenuLi.length; i++) {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
//缓慢移动到:
// 总时间(duration)500ms;
// 频率(interval)10ms:
// 总距离(target):锚点间距
// 步长(step):target/duration*interval
leftMenuLi[i].onclick = function(i) {
return function() {
var duration = 500;
var interval = 100;
var distance = Math.abs(anchor[i] - scrollTop);
var step = distance / duration * interval;
var timer = setInterval(function() {
if (Math.abs(scrollTop - anchor[i]) < step) {
console.log("1-s->" + scrollTop); //1588.999995
console.log("2-a->" + anchor[i]);
document.documentElement.scrollTop = anchor[i];
document.body.scrollTop = anchor[i];
//scrollTop=anchor[i];
console.log("You are here");
window.clearInterval(timer);
console.log("doc"+document.body.scrollTop)
return;
} else if (anchor[i] > (scrollTop)) {
scrollTop += step
document.documentElement.scrollTop = scrollTop;
document.body.scrollTop = scrollTop;
} else if (anchor[i] < (scrollTop)) {
scrollTop -= step
document.documentElement.scrollTop = scrollTop;
document.body.scrollTop = scrollTop;
}
}, interval);
}
}(i);
}

跑马灯

图33
难点
怎样实现滑动内容结束到从新开始不出现闪动:
原理:把内容复制一份
当endbox的开头运动到显示盒子开头时,让scrollLeft=0,此刻显示beginbox的开头