1 <script> 2 myTool.$('btn1').onclick = function () { 3 // myTool.$('box').style.background = 'green'; 4 myTool.changeCssStyle(myTool.$('box'), 'background', 'green'); 5 }; 6 7 myTool.$('btn2').onclick = function () { 8 // myTool.$('box').style.width = '1000px'; 9 myTool.changeCssStyle(myTool.$('box'), 'width', '1000px') 10 }; 11 12 changeCssStyle (eleObj, attr, value) { 13 eleObj.style[attr] = value; 14 } 15 </script>
1 console.log(myTool.getStyleAttr(box, 'width')); 2 console.log(myTool.getStyleAttr(box, 'height')); 3 console.log(myTool.getStyleAttr(box, 'border')); 4 console.log(myTool.getStyleAttr(box, 'backgroundColor'));
不需要是行内
1 getStyleAttr(obj, attr) { 2 if (obj.currentStyle) { // IE 和 opera 3 return obj.currentStyle[attr]; 4 } else { 5 return window.getComputedStyle(obj, null)[attr]; 6 } 7 }
1 <script> 2 window.addEventListener('load', function (ev) { 3 var box = myTool.$('box'); 4 5 myTool.$('btn').addEventListener('click', function () { 6 buffer(box, 'left', 800); 7 }); 8 9 myTool.$('btn1').addEventListener('click', function () { 10 buffer(box, 'width', 800); 11 }); 12 }); 13 14 /** 15 * 缓动动画函数 16 * @param {Object}eleObj 17 * @param {String}attr 18 * @param {String | Number}target 19 */ 20 function buffer(eleObj, attr, target) { 21 // 1.1 先清后设 22 clearInterval(eleObj.timer); 23 24 // 1.2 定义变量 25 var speed = 0, begin; 26 27 // 1.2 设置定时器 28 eleObj.timer = setInterval(function () { 29 // 获取要做动画属性的初始值 parseInt字符串转数字 30 begin = parseInt(myTool.getStyleAttr(eleObj, attr)); 31 console.log('begin:' + begin); 32 33 34 // 2.3 求出步长 35 speed = (target - begin) * 0.2; 36 speed = (target > begin) ? Math.ceil(speed) : Math.floor(speed); 37 38 // 2.4 动起来 39 eleObj.style[attr] = begin + speed + 'px'; 40 eleObj.innerText = begin; 41 42 // 2.5 清除定时器 43 if (begin === target) { 44 clearInterval(eleObj.timer); 45 } 46 }, 20); 47 } 48 </script>