您的位置:首页 > Web前端 > JavaScript

JavaScript滚动条的制作

2014-11-04 19:47 369 查看

效果演示

这个效果的制作是借助setTimeout的第三个参数。setTimeout/setInterval,这两个函数相信前端开发同学都很熟悉。它们在非IE(6-9)浏览器中还可以如下使用:

view source

print?

1
setTimeout(
function
(obj){
2
alert(obj.a);
3
}, 2000, {a:1});
即传了第三个参数,第三个参数将作为回调函数的参数obj传入。在非IE浏览器中都弹出了1。这样有个好处,即解决了回调函数的执行上下文,比如要调用某个对象的某个方法,即可以通过参数把该对象传进去。


view source

print?

1
setTimeout(
function
(obj){
2
obj.method();
3
}, 2000, obj);
上次看到一个setTimeout的一个用法:

view source

print?

1
var
arr = [1,9,2,8,3,7,4,6,4,5];
2
for
(
var
i = 0, len = arr.length; i < len; i++){
3
setTimeout(
function
(x){
4
console.log(x);
5
},arr[i],arr[i]);
6
}
虽然这个并不是什么好的用法,这里setTimeout的第三个参数主要得到了除IE外的系列浏览器的支持。

要让IE支持的话,可以按下面方法进行扩展:

view source

print?

01
(
function
(w){
02
//ie传入第三个参数
03
if
(!+[1,]){
//除IE外,!+[1,]都是返回false
04
(
function
(overrideFn){
05
w.setTimeout = overrideFn(w.setTimeout);
06
w.setInterval = overrideFn(w.setInterval);
07
})(
function
(originalFn){
08
return
function
(code,delay){
09
var
args = Array.prototype.slice.call(arguments,2);
10
return
originalFn(
function
(){
11
if
(
typeof
code ==
'string'
){
12
eval(code);
13
}
else
{
14
code.apply(
this
,args);
15
}
16
},delay);
17
}
18
})
19
}
20
})(window)
如果有第三个参数,某些情况下的调用就可以方便的处理回调函数中当前对象的问题,写起来好看点。扩展一下Function,增加一个延时调用(参考而已):

view source

print?

01
function
.prototype.delay =
function
(){
02
var
args = Array.prototype.slice.call(arguments,0);
03
setTimeout(
function
(fn){
04
fn.apply(
''
,args.slice(1));
05
},args[0],
this
);
06
}
07
var
fn =
function
(x){
08
alert(x)
09
};
10
fn.delay(1000,
'xesam'
);
下面是模拟进度条的代码:

view source

print?

01
<script type=
"text/javascript"
>
02
function
Load(id,width){
03
this
.ele = document.getElementById(id);
04
this
.indicator = document.createElement(
'div'
);
05
this
.width = (width > 0 && width) || 300;
06
this
.init();
07
}
08
Load.prototype = {
09
constructor:Load,
10
init:
function
(){
11
this
.ele.style.width =
this
.width +
'px'
;
12
this
.ele.appendChild(
this
.indicator);
13
var
iStyle =
this
.indicator.style;
14
iStyle.width = 0;
15
iStyle.height =
'100%'
;
16
iStyle.background =
'#ff5500'
;
17
},
18
start:
function
(){
19
//this.init();
20
this
.loading();
21
},
22
loading:
function
(){
23
this
.timer = setTimeout(
function
(obj){
24
var
t = obj.indicator.data || 0;
25
if
(t < obj.width){
26
obj.indicator.style.width = t + 1 +
'px'
;
27
obj.indicator.data = t + 1;
28
obj.loading();
29
}
else
{
30
clearInterval(obj.timer);
31
}
32
},10,
this
);
33
},
34
stop:
function
(){
35
clearTimeout(
this
.timer);
36
}
37
}
38
var
load_1 =
new
Load(
'loading'
,300);
39
load_1.start();
40
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: