原生js获取元素的属性值

今天在用原生js获取div的margin时候遇到了困难,然后记录下来,以免下次解决不了类似问题。
var box = document.querySelector("div");
console.log(getStyle(box, "marginTop"));
function getStyle(ele, attr) {
        if (window.getComputedStyle) {
          return window.getComputedStyle(ele, null)[attr];
        } else {
          return ele.currentStyle[attr];
        }
      }

  

 
posted @ 2020-03-27 14:12  ayong6  阅读(2717)  评论(0)    收藏  举报