设置dom节点属性的代码优化
需求:某dom节点在正常情况下,有设置其transition-duration为1s,在mousemove时候,要去掉其transition-duration设置的时间,在mouseup时候,恢复其transition-duration时间为1s。
考虑到兼容性,故设置的属性相关属性有:
transition-duration
-moz-transition-duration
-webkit-transition-duration
-o-transition-duration
最初代码逻辑:
switch(evt.type) { case "mousedown": //XXXX break; case "mousemove": dom1.setStyle('transition-duration', '0s'); dom1.setStyle('-moz-transition-duration', '0s'); dom1.setStyle('-webkit-transition-duration', '0s'); dom1.setStyle('-o-transition-duration', '0s'); dom2.setStyle('transition-duration', '0s'); dom2.setStyle('-moz-transition-duration', '0s'); dom2.setStyle('-webkit-transition-duration', '0s'); dom2.setStyle('-o-transition-duration', '0s'); //XXXX break; case "mouseup": dom1.setStyle('transition-duration', '1s'); dom1.setStyle('-moz-transition-duration', '1s'); dom1.setStyle('-webkit-transition-duration', '1s'); dom1.setStyle('-o-transition-duration', '0s'); dom2.setStyle('transition-duration', '1s'); dom2.setStyle('-moz-transition-duration', '1s'); dom2.setStyle('-webkit-transition-duration', '1s'); dom2.setStyle('-o-transition-duration', '1s'); //XXXX break; }
明显看到上述代码特别冗余,故抽出一个函数来干这些事情
setTransitionDuration: function(element, seconds) { if (!element) { return; } seconds = (seconds ? seconds : 0) + 's'; element.setStyle('transition-duration', seconds); element.setStyle('-moz-transition-duration', seconds); element.setStyle('-webkit-transition-duration', seconds); element.setStyle('-o-transition-duration', seconds); } //则上述代码可直接调用: case "mousemove": this.setTransitionDuration(dom1, 0); this.setTransitionDuration(dom2, 0); break; case "mouseup": this.setTransitionDuration(dom1, 1); this.setTransitionDuration(dom2, 1); break;
相对于第一种方案,明显好很多了,再继续优化,将设置的属性写在一个class中,然后直接addClass/removeClass即可,这样,样式的代码放置于css文件中,js代码关注与自己的逻辑,更加清晰
//css样式代码 .transition-duration-stop { transition-duration: 0s; -moz-transition-duration: 0s; -webkit-transition-duration: 0s; -o-transition-duration: 0s; } //js代码 case "mousemove": dom1.addClass('transition-duration-stop'); dom2.addClass('transition-duration-stop'); break; case 'mouseup': dom1.removeClass('transition-duration-stop'); dom2.removeClass('transition-duration-stop'); break;
大功告成