【前端】鼠标捕获元素信息

function getElementXPath(element) {
        if (element.id !== '') {
            return '//*[@id="' + element.id + '"]';
        }
        if (element === document.body) {
            return '/html/body';
        }

        var ix = 0;
        var siblings = element.parentNode.childNodes;
        for (var i = 0; i < siblings.length; i++) {
            var sibling = siblings[i];
            if (sibling === element) {
                return getElementXPath(element.parentNode) + '/' + element.tagName.toLowerCase() + '[' + (ix + 1) + ']';
            }
            if (sibling.nodeType === 1 && sibling.tagName === element.tagName) {
                ix++;
            }
        }
    }

    document.addEventListener('mouseover', function(event) {
        if (event.target) {
            event.target.style.outline = '2px solid red';
        }
    }, false);

    document.addEventListener('mouseout', function(event) {
        if (event.target) {
            event.target.style.outline = '';
        }
    }, false);

    document.addEventListener('click', function(event) {
        event.preventDefault();
        event.stopPropagation();
        if (event.target) {
            var xpath = getElementXPath(event.target);
            console.log('Element clicked: ', event.target);
            console.log('Tag name: ' + event.target.tagName);
            console.log('Class: ' + event.target.className);
            console.log('ID: ' + event.target.id);
            console.log('XPath: ' + xpath);
        }
    }, false);

 

posted @ 2024-05-20 18:18  Hello霖  阅读(6)  评论(0编辑  收藏  举报