链式调用

才在JS里写CSS的时候,遇到了个比较恶心的问题

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
this.createItem = function (text){
return $c('div', function (ele){
ele.append('div', function (contentEle){
contentEle[0].className = 'content';
if ( typeof text === 'string' ){
contentEle.text(text);
}else{
contentEle.append(text);
}
contentEle.css({
'position': 'relative'
});
});
ele.css({
'position': 'relative'
});
ele.append($c('div', function (closeTag){
closeTag[0].className = 'closeTag';
closeTag.text('x');
closeTag.css({
'position': 'absolute',
'right': '0px',
'top': '0px',
'cursor': 'pointer'
});
}))
});
};

那段css({})。。。。。。。打起来发现有点那啥的…………

于是想起来以前听闻过的 链式调用 ,遂马上开写

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
var cssLine = function (ele){
var keys = Object.keys(ele[0].style);
var obj = new function (){
var cssObj = this;
this.lineEnd = function (){
return ele;
};
for ( var i in keys )
this[ keys[i] ] = function (key){
return function (set){
ele[0].style[key] = set;
return cssObj;
}
}(keys[i]);
};
return obj;
};
//use
cssLine(document.querySelectorAll('body'))
.transition('opacity 1s')
.opacity(0.5);
setTimeout(function (){
cssLine(document.querySelectorAll('body'))
.transition('opacity 1s')
.opacity('1');
}, 1000);

好吧,这样写确实优雅了很多……而且简洁明了