通过使用此模块,只需将鼠标悬停在浏览器中,即可快速查看DOM元素的属性。基本上它是一个即时检查器。
将鼠标悬停在 DOM 元素上会显示其属性!
复制下面的整个代码块,并将其粘贴到浏览器 Web 控制台中。现在将鼠标悬停在你正在浏览的任何网页上。看到了什么?
1(function SpyOn() {
2
3 const _id = 'spyon-container',
4 _posBuffer = 3;
5
6 function init() {
7 document.body.addEventListener('mousemove', glide);
8 document.body.addEventListener('mouseover', show);
9 document.body.addEventListener('mouseleave', hide);
10 }
11
12 function hide(e) {
13 document.getElementById(_id).style.display = 'none';
14 }
15
16 function show(e) {
17 const spyContainer = document.getElementById(_id);
18 if (!spyContainer) {
19 create();
20 return;
21 }
22 if (spyContainer.style.display !== 'block') {
23 spyContainer.style.display = 'block';
24 }
25 }
26
27 function glide(e) {
28 const spyContainer = document.getElementById(_id);
29 if (!spyContainer) {
30 create();
31 return;
32 }
33 const left = e.clientX + getScrollPos().left + _posBuffer;
34 const top = e.clientY + getScrollPos().top + _posBuffer;
35 spyContainer.innerHTML = showAttributes(e.target);
36 if (left + spyContainer.offsetWidth > window.innerWidth) {
37 spyContainer.style.left = left - spyContainer.offsetWidth + 'px';
38 } else {
39 spyContainer.style.left = left + 'px';
40 }
41 spyContainer.style.top = top + 'px';
42 }
43
44 function getScrollPos() {
45 const ieEdge = document.all ? false : true;
46 if (!ieEdge) {
47 return {
48 left : document.body.scrollLeft,
49 top : document.body.scrollTop
50 };
51 } else {
52 return {
53 left : document.documentElement.scrollLeft,
54 top : document.documentElement.scrollTop
55 };
56 }
57 }
58
59 function showAttributes(el) {
60 const nodeName = `<span style="font-weight:bold;">${el.nodeName.toLowerCase()}</span><br/>`;
61 const attrArr = Array.from(el.attributes);
62 const attributes = attrArr.reduce((attrs, attr) => {
63 attrs += `<span style="color:#ffffcc;">${attr.nodeName}</span>="${attr.nodeValue}"<br/>`;
64 return attrs;
65 }, '');
66 return nodeName + attributes;
67 }
68
69 function create() {
70 const div = document.createElement('div');
71 div.id = _id;
72 div.setAttribute('style', `
73 position: absolute;
74 left: 0;
75 top: 0;
76 width: auto;
77 height: auto;
78 padding: 10px;
79 box-sizing: border-box;
80 color: #fff;
81 background-color: #444;
82 z-index: 100000;
83 font-size: 12px;
84 border-radius: 5px;
85 line-height: 20px;
86 max-width: 45%;
87 `
88 );
89 document.body.appendChild(div);
90 }
91
92 init();
93
94})();
此模块以 IIFE 的形式实现。这样只要需要一些 DOM 监视辅助,就可以将代码复制并粘贴到 Web 控制台中。将 div 插入到文档的正文中,并在正文上启用鼠标事件侦听器。从目标元素中检索属性,将其简化为单个字符串,最后在工具提示中显示。
你可以在这里【https://github.com/eddieherm/spyon】找到源代码,希望你能做得更好!也许你不希望将其作为 IIFE 来实现,或者是去显示其他数据。