为了账号安全,请及时绑定邮箱和手机立即绑定

使用JS 遍历 json时遇到的问题。attr.step为什么是undefined。

使用JS 遍历 json时遇到的问题。attr.step为什么是undefined。

地狱快车_666 2016-08-24 14:28:45
<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Title</title>     <script>  function getStyle(obj,attr){      if (obj.currentStyle){          return obj.currentStyle[attr];      }else{         return window.getComputedStyle(obj,null)[attr];      }  }  function  animate_arg(obj,json,speed){      for(var attr in json){    var current = parseInt(getStyle(obj,attr));    console.log(attr);      console.log(typeof(attr));      //比如此处传josn{top:500}进来的时候console.log(attr)就是输出top,那下面attr.step json的值传进来就会生成相应的      //width.step,height.step,left.step 但是我实际我attr.step得到的是个未定义的。      attr.step = json[attr]>current ? speed : -speed;      console.log(typeof(attr.step));            attr.timer = setInterval(function(){    var current = parseInt(getStyle(obj,attr));      var result = Math.abs(json[attr] - current);          if (result <= speed){          obj.style[attr]=json[attr];          }else{          obj.style[attr]= current + attr.step + "px";          }     },30)    }   }    window.onload=function(){      var btn200 = document.getElementById("btn200");      var btn400 = document.getElementById("btn400");      var box = document.getElementById("box");      btn200.onclick = function() {          animate_arg(box,{width: 200, top: 800,left: 200},10);      };      btn400.onclick = function() {         animate_arg(box,{top:500},10);       }    }     </script>     <style>          div {              width: 100px;              height: 100px;              background-color: pink;              position: absolute;              left: 0;              top: 50px;              border-radius: 50%;          }     </style> </head> <body>     <button id="btn200">200</button>     <button id="btn400">400</button>     <div id="box"></div> </body> </html>
查看完整描述

2 回答

?
地狱快车_666

TA贡献4条经验 获得超0个赞

原因在于attr不是对象或数组不能添加属性

查看完整回答
反对 回复 2016-08-26
?
qq_sU_4

TA贡献30条经验 获得超6个赞

为什么要attr.step,直接var 个 step不可以吗

查看完整回答
反对 回复 2016-08-25
  • 地狱快车_666
    地狱快车_666
    json会传多个值进来,可能是width,left,height等等,你直接用step不能区分,你下面函数里for循环的时候用width.step,left.step才能区分吧。
  • 2 回答
  • 0 关注
  • 1339 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信