问答详情
源自:6-2 完美运动框架

为什么我的当前值会比目标值差1px

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Document</title>

</head>

<style>

ul li{

width: 100px;

height: 100px;

background: yellow;

border: 1px solid #000;

list-style: none;

margin-bottom: 20px;

filter: alpha(opacity:30);

opacity: 0.3;

/* position: fixed;

right: 500px;

bottom: 300px; */

}

</style>

<body>

<ul>

<li id="li1"></li>

<!-- <li id="li2"></li> -->

</ul>

<script>

window.onload = function(){

// var li = document.getElementsByTagName('li');

// for(var i=0;i<li.length;i++){

//  //给每个li配一个定时器

//  li[i].timer

//  li[i].onmouseover= function(){

//  start(this,400);

//  };

//  li[i].onmouseout= function(){

//  start(this,200);

//  }

// };

var li1 = document.getElementById('li1');

var li2 = document.getElementById('li2');

li1.onmouseover = function(){

start(li1,{width:300},function(){

alert(1)

});

};

li1.onmouseout = function(){

start(this,{width:100});

};

// li2.onmouseover = function(){

//  start(this,'height',400);

// };

// li2.onmouseout = function(){

//  start(this,'height',100);

// };

}

//获取样式

function getStyle(obj,attr){

if(obj.currentStyle){

return obj.currentStyle[attr];

}else{

return getComputedStyle(obj,false)[attr];

}

}

function start(obj,json,fn){

var flag = true;

clearInterval(obj.timer);

obj.timer = setInterval(function(){

for(var attr in json){

var cur = 0;

if(attr=='opacity'){

cur = Math.round(parseFloat(getStyle(obj,attr))*100);

}else{

cur = parseInt(getStyle(obj,attr));

};


var speed = (json[attr]-cur)/8;

speed = speed>0?Math.ceil(speed):Math.floor(speed);

if(json[attr]!=cur){

flag = false;

// console.log(flag);

console.log('目标值'+json[attr]);

console.log('现在值'+cur)

};

//obj.style.width===obj.style[width],这里要写成这样!!!

if(attr=='opacity'){

obj.style.filter = 'alpha(opacity:'+(cur+speed)+')';

obj.style.opacity = (cur+speed)/100;

}else{

obj.style[attr] = cur+speed+'px';

};

   };

      if(flag){

    clearInterval(obj.timer);

    if(fn){

    fn()

    };

   };  

},30)

}



</script>

</body>

</html>


提问者:成功唯有积累 2016-12-26 19:17

个回答

  • qq_12月_0
    2016-12-26 20:01:34

    用审查元素没少呀  

  • qq_12月_0
    2016-12-26 19:57:53

    说清楚 什么参数比目标值低