2017-07-08 29 views
-1

有沒有什麼方法可以用JavaScript來檢查元素,就像FireBug或DevTool一樣?事情是這樣的:用JS檢查對象

enter image description here

+0

如果我正確地解釋你的問題,我想檢查元素時,使用Javascript將被執行,其結果將被渲染。如果您查看頁面源,則只能看到腳本本身。 –

+0

按下Ctrl/Cmd + Shift + C並選擇要檢查的元素,然後轉到'Style','Computed'等旁邊的'Properties'選項卡。 – tom10271

回答

1

您可以模擬使用JavaScript,檢查與來自僞類,如:after創建僞元素除外。

所有顯示的都是元素的tagName,id,classList和dimensions,它們都可以通過元素的屬性和計算樣式屬性獲得;

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>

+0

謝謝!這正是我需要的! –