// ==UserScript== // @name 通过鼠标右键获取DOM和元素选择器 // @namespace http://tampermonkey.net/ // @version 0.3 // @description 牛逼ProMax // @author Luhuipeng // @match *://*/* // @icon https://www.google.com/s2/favicons?sz=64&domain=tampermonkey.net // @license MIT // @downloadURL none // ==/UserScript== (function() { 'use strict'; // 通过DOM元素获取元素选择器 let selector, x, y, visible = false 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) { x = event.clientX, y = event.clientY; let element = document.elementFromPoint(x, y); console.log('x:', x, 'y:', y) return element } // 鼠标点击事件 function track_mouse (event) { if (event.button == 2) { if (visible) return visible = true var elementMouseIsOver = get_current_element(event) console.log('当前鼠标指向的元素是:', elementMouseIsOver) selector = getSelectorRes(elementMouseIsOver) console.log('result:', selector) const matchResult = elementMouseIsOver if (matchResult) { console.log(document.querySelector(selector)) copyToClipboard(selector) showConfirm() } else { // 写入剪贴板 console.log('未匹配到元素') } } } // 选择按钮的弹窗 function showConfirm () { const confirm = document.createElement('div') confirm.innerHTML = `

复制

元素选择器 or x/y坐标?

` confirm.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(confirm) const cancel = confirm.querySelector('.confirm-btn-cancel') const ok = confirm.querySelector('.confirm-btn-ok') cancel.addEventListener('click', () => { document.body.removeChild(confirm) copyToClipboard(selector) visible = false }) ok.addEventListener('click', () => { document.body.removeChild(confirm) copyToClipboard(`x:${x},y:${y}`) visible = false }) } window.oncontextmenu = function (e) { e.preventDefault() } window.onmousedown = track_mouse // Your code here... })();