1. 程式人生 > 實用技巧 >一段監視 DOM 的神奇程式碼

一段監視 DOM 的神奇程式碼

通過使用此模組,只需將滑鼠懸停在瀏覽器中,即可快速檢視DOM元素的屬性。基本上它是一個即時檢查器。

將滑鼠懸停在 DOM 元素上會顯示其屬性!

自己嘗試一下

複製下面的整個程式碼塊,並將其貼上到瀏覽器Web 控制檯中。現在將滑鼠懸停在你正在瀏覽的任何網頁上。看到了什麼?

(function SpyOn() {

  const _id = 'spyon-container',
        _posBuffer = 3;

  function init() {
    document.body.addEventListener('mousemove', glide);
    document.body.addEventListener('mouseo
ver', 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>${el.nodeName.toLowerCase()}</span><br/>`; const attrArr = Array.from(el.attributes); const attributes = attrArr.reduce((attrs, attr) => { attrs += `<span>${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 插入到文件的正文中,並在正文上啟用滑鼠事件偵聽器。從目標元素中檢索屬性,將其簡化為單個字串,最後在工具提示中顯示。

廣州品牌設計公司https://www.houdianzi.com PPT模板下載大全https://redbox.wode007.com

用例

  1. 幫助解決UI錯誤
  2. 確保你所應用的 DOM 元素能夠按預期工作(比如點選獲得正確的類,等等)
  3. 瞭解一個 Web 應用的結構

你可以從這段程式碼中學到什麼

  1. 如何使用 Vanillajs實現工具提示模組
  2. 如何解析 DOM 物件的屬性
  3. 如何找到滑鼠 X 和 Y 的位置
  4. 如何獲取文件的滾動位置
  5. 瞭解不同瀏覽器的行為方式 —— Edge vs. Chrome vs. Safari