0

图片描述

为什么我在移出来的时候,他还是一闪一闪的不停。代码一模一样。为何会错呀?求大神解答。

老谭 1.2k
2015-03-22 提问
2 个回答
0

已采纳
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
body{margin:0; padding:0;}
#div1{width:100px; height:100px; background:#06c; position:absolute; border:1px solid #000; opacity:0.3; filter:alpha(opacity=30);}
</style>
<script>
window.onload = function(){
  var run = document.getElementById("div1");
  var speed = 1;
  var timer = null;
  var alpha=0.3;
  run.onmouseover = function(){
    startrun(1);
  }
  run.onmouseout = function(){
    startrun(0.3);
  }
  function startrun(target){
    var run = document.getElementById("div1");
    clearInterval(timer);
    var seped = 0;
    timer = setInterval(function(){
      if(target > alpha){
        speed = 0.1;
      }else{
        speed = -0.1;
      }

      if(alpha == target){
        clearInterval(timer);
      }
      else{
        alpha = alpha + speed;
        run.style.opacity = alpha;
        document.title = alpha;
      }
    },30)
  }
}

</script>
</head>

<body>
<div id="div1"></div>
</body>
</html

你把这段运行一下,看下标题栏的透明度变化,因为JS的小数相加的问题,即0.1+0.1 != 0.2,所以你最后是达不到目的值得,只会在周围跳动,你应该把它变成整数再相加,最后再除100赋值就好了。如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
body{margin:0; padding:0;}
#div1{width:100px; height:100px; background:#06c; position:absolute; border:1px solid #000; opacity:0.3; filter:alpha(opacity=30);}
</style>
<script>
window.onload = function(){
  var run = document.getElementById("div1");
  var speed = 1;
  var timer = null;
  var alpha=30;
  run.onmouseover = function(){
    startrun(100);
  }
  run.onmouseout = function(){
    startrun(30);
  }
  function startrun(target){
    var run = document.getElementById("div1");
    clearInterval(timer);
    var seped = 0;
    timer = setInterval(function(){
      if(target > alpha){
        speed = 1;
      }else{
        speed = -1;
      }

      if(alpha == target){
        clearInterval(timer);
      }
      else{
        alpha = alpha + speed;
        run.style.opacity = alpha/100;
        document.title = alpha;
      }
    },30)
  }
}

</script>
</head>

<body>
<div id="div1"></div>
</body>
</html

这个知识点是js中小数的四则运算精度会丢失问题:http://www.iteye.com/problems/71491

这里也有其他的解决方法

0

时间间隔太短了吧 你把间隔时间改成3000

撰写答案

推广链接