做者:Eddie Aich翻译:疯狂的技术宅javascript
原文:https://dev.to/eddieaich/spy-...前端
未经容许严禁转载java
经过使用此模块,只需将鼠标悬停在浏览器中,便可快速查看DOM元素的属性。基本上它是一个即时检查器。node
将鼠标悬停在 DOM 元素上会显示其属性!git
复制下面的整个代码块,并将其粘贴到浏览器 Web 控制台中。如今将鼠标悬停在你正在浏览的任何网页上。 看到了什么?程序员
(function SpyOn() { const _id = 'spyon-container', _posBuffer = 3; function init() { document.body.addEventListener('mousemove', glide); document.body.addEventListener('mouseover', show); document.body.addEventListener('mouseleave', hide); } function hide(e) { document.getElementById(_id).style.display = 'none'; } function show(e) { const spyContainer = document.getElementById(_id); if (!spyContainer) { create(); return; } if (spyContainer.style.display !== 'block') { spyContainer.style.display = 'block'; } } function glide(e) { const spyContainer = document.getElementById(_id); if (!spyContainer) { create(); return; } const left = e.clientX + getScrollPos().left + _posBuffer; const top = e.clientY + getScrollPos().top + _posBuffer; spyContainer.innerHTML = showAttributes(e.target); if (left + spyContainer.offsetWidth > window.innerWidth) { spyContainer.style.left = left - spyContainer.offsetWidth + 'px'; } else { spyContainer.style.left = left + 'px'; } spyContainer.style.top = top + 'px'; } function getScrollPos() { const ieEdge = document.all ? false : true; if (!ieEdge) { return { left : document.body.scrollLeft, top : document.body.scrollTop }; } else { return { left : document.documentElement.scrollLeft, top : document.documentElement.scrollTop }; } } function showAttributes(el) { const nodeName = `<span style="font-weight:bold;">${el.nodeName.toLowerCase()}</span><br/>`; const attrArr = Array.from(el.attributes); const attributes = attrArr.reduce((attrs, attr) => { attrs += `<span style="color:#ffffcc;">${attr.nodeName}</span>="${attr.nodeValue}"<br/>`; return attrs; }, ''); return nodeName + attributes; } function create() { const div = document.createElement('div'); div.id = _id; div.setAttribute('style', ` position: absolute; left: 0; top: 0; width: auto; height: auto; padding: 10px; box-sizing: border-box; color: #fff; background-color: #444; z-index: 100000; font-size: 12px; border-radius: 5px; line-height: 20px; max-width: 45%; ` ); document.body.appendChild(div); } init(); })();
此模块以 IIFE 的形式实现。这样只要须要一些 DOM 监视辅助,就能够将代码复制并粘贴到 Web 控制台中。将 div 插入到文档的正文中,并在正文上启用鼠标事件侦听器。从目标元素中检索属性,将其简化为单个字符串,最后在工具提示中显示。github
你能够在这里找到源代码,但愿你能作得更好!也许你不但愿将其做为 IIFE 来实现,或者是去显示其余数据。面试