方才在JS里写CSS的时候,遇到了个比较恶心的问题
12345678910111213141516171819202122232425262728293031 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({})
。。。。。。。打起来发现有点那啥的…………
于是想起来以前听闻过的 链式调用
,遂马上开写
123456789101112131415161718192021222324252627282930var 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;};//usecssLine(document.querySelectorAll('body')) .transition('opacity 1s') .opacity(0.5);setTimeout(function (){ cssLine(document.querySelectorAll('body')) .transition('opacity 1s') .opacity('1');}, 1000);
好吧,这样写确实优雅了很多……而且简洁明了