Greasy Fork

来自缓存

通过鼠标右键获取DOM和元素选择器

牛逼Plus

目前为 2023-02-22 提交的版本。查看 最新版本

// ==UserScript==
// @name         通过鼠标右键获取DOM和元素选择器
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  牛逼Plus
// @author       Luhuipeng
// @match        *://*/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=tampermonkey.net
// @license MIT
// ==/UserScript==

(function() {
    'use strict';
// 通过DOM元素获取元素选择器
function getSelectorRes (el) {
  if (!(el instanceof Element)) return
  const path = []
  while (el.nodeType === Node.ELEMENT_NODE) {
    let selector = el.nodeName.toLowerCase()
    if (el.id) {
      selector += '#' + el.id
      path.unshift(selector)
      break
    } else {
      let sib = el,
        nth = 1
      while ((sib = sib.previousElementSibling)) {
        if (sib.nodeName.toLowerCase() == selector) nth++
      }
      if (nth != 1) selector += ':nth-of-type(' + nth + ')'
    }
    path.unshift(selector)
    el = el.parentNode
  }
  return path.join('>')
}
// 写入剪贴板
function copyToClipboard (text) {
  var input = document.createElement('input');
  input.setAttribute('value', text);
  document.body.appendChild(input);
  input.select();
  if (document.execCommand('copy')) {
    document.execCommand('copy');
  }
  document.body.removeChild(input);
}
// 获取当前鼠标指向的元素
function get_current_element (event) {
  var x = event.clientX, y = event.clientY,
    element = document.elementFromPoint(x, y);
  return element
}
// 鼠标点击事件
function track_mouse (event) {
  if (event.button == 2) {
    var elementMouseIsOver = get_current_element(event)
    console.log('当前鼠标指向的元素是:', elementMouseIsOver)
    const res = getSelectorRes(elementMouseIsOver)
    console.log('result:', res)
    const matchResult = elementMouseIsOver
    if (matchResult) {
      console.log(document.querySelector(res))
      copyToClipboard(res)
      showTip()
    } else {
      // 写入剪贴板
      console.log('未匹配到元素')
    }
  }
}

// 悬浮提示
function showTip () {
  const tip = document.createElement('div')
  tip.innerHTML = '元素选择器 已复制到剪贴板'
  // 元素水平居中 位置固定
  tip.style.cssText = `
    position: fixed;
    top: 40%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: #000;
    color: #fff;
    padding: 10px 16px;
    font-size: 18px;
    font-weight: bold;
    border-radius: 5px;
    z-index: 9999;
    opacity: 0.8;
  `
  document.body.appendChild(tip)
  setTimeout(() => {
    document.body.removeChild(tip)
  }, 2000)
}

window.oncontextmenu = function (e) {
  e.preventDefault()
}
window.onmousedown = track_mouse
    // Your code here...
})();