window.getComputedStyle(节点,节点后面伪元素)[“css的属性”]#### 考虑到两种情况需要封装一个函数
function getStyle(ele,attr){
//传入的两个参数分别是节点和属性
return window.getComputed ? window.getComputedStyle(ele,null)[attr]:ele.currentStyle[attr];
}
<style>
*{
margin:0;
padding:0;
}
.box{
width: 300px;
height: 300px;
background-color: #0099ff;
}
</style>
</head>
<body>
<button class="btn">触发</button>
<div class="box"></div>
<script>
var box = document.querySelector(".box");
//.style设置的是行内样式
//考虑到两种情况需要封装一个函数
function getStyle(ele,attr){
//传入的两个参数分别是节点和属性
return window.getComputed ? window.getComputedStyle(ele,null)[attr]:ele.currentStyle[attr];
}
</script>
可以上下移动的动画效果
变速动画中的left全部改为attr
<scirpt>
//传入的节点,属性值和位置
function animate(element,attr,position){
//每次调用都会操作同一个计时器,需要先清除一下
clearInterval(element.timer);
//定时器挂在节点上
element.timer = setInterval(function (){
var current = parseInt(getStyle(element,attr));
// var current = element.offsetLeft;
//如何变速取决于每次加的大小
var step = (position - current)/10;
//判断,如果大于0就向上取整,如果小于0,就向下取整
step = step > 0 ? Math.ceil(step) : Math.floor(step);
if(Math.abs(current - position) > step){
element.style[attr] = current + step +"px";
}else{
element.style[attr] = position + "px";
clearInterval(element.timer);
}
},20)
}
</scirpt>
第二种,传入的是json对象,不兼容,可能有bug
<script>
function animate(element,json){
clearInterval(element.timer);
element.timer = setInterval(function (){
//json对象格式的遍历需要for in
for(var item in json){
//获取对象的样式,传入节点和属性
var current = parseInt(getStyle(element,item));
console.log("current",current);
//获取目标的位置
var position = json[item];
//及收入判断,实际的值不等于目标的值,就继续运行
if(current != position){
var step = (position-current)/10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
if(Math.abs(current -position) >step){
element.style[item] = current +step +"px";
}else{
element.style[item] = position + "px";
clearInterval(element.timer);
}
}
}
},20)
}
</script>