用JS检查对象

时间:2017-07-08 01:44:06

标签: javascript

有没有办法用JavaScript检查元素,就像FireBug或DevTool一样?像这样:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用javascript来模拟它,但检查从伪类:after创建的伪元素除外。

所有显示的是元素的tagName,id,classList和dimension,它们都可以通过元素的属性和计算出的样式属性获得;

var tag = element.tagName.toLowerCase();
var id = element.id;
var classes = element.classList.toString();
var width = window.getComputedStyle( element ).width;
var height = window.getComputedStyle( element ).height;

演示,不是最好的,但说明了它的用途



document.addEventListener("mouseover", function(e) {
  var element = e.target;
  var tag = element.tagName.toLowerCase();
  var id = element.id ? "#"+element.id:"";
  var classes = element.classList.toString().replace(/\s/, ".");
  classes = classes ? "."+classes:"";
  var width = window.getComputedStyle(element).width;
  var height = window.getComputedStyle(element).height;
  element.setAttribute("data-tooltip", `${tag}${id}${classes} ${width} x ${height}`);
});

* {
  position: relative;
}

*:not(body):not(html):hover:after {
  content: attr(data-tooltip);
  display: block;
  position: absolute;
  top: -20px;
  left: 0px;
  background: black;
  color: white;
  font-size: 10px;
  padding:6px;
  white-space: nowrap;
}

<div class="class1 class2">
  This is some text
  <table id="table" class="someclass">
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
    </tr>
    <tr>
      <td id="cell1">Data 1</td>
      <td>Data 2</td>
    </tr>
    <tr>
      <td>Data 3</td>
      <td>Data 4</td>
    </tr>
    <tr>
      <td>Data 6</td>
      <td>Data 5</td>
    </tr>
  </table>
</div>
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
</ul>
&#13;
&#13;
&#13;