简体   繁体   中英

How to highlight HTML element on mouse click?

Is it possible to write code in JavaScript that highlights the borders of the HTML element on which the mouse pointer stands (or clicks), in a similar way to what Firebug does, but without the use of a browser extension but rather rely on JavaScript alone?

If so, is it possible to get the relevant element from HTML code after the mouse click on element?

[edit] Thanks for the answers! is it possible to run those examples on external page (rather than on a page that I created) without the use of things like GreaseMonkey?

Here is a simple example. You should be able to build upon this:

document.onclick = function(e) {
    var event = e || window.event;

    // this is the element you want:
    var target = e.target || e.srcElement;
}

This method would probably be more preferred:

var hilightElement = function(e) {
    var event = e || window.event;

    // this is the element you want:
    var target = e.target || e.srcElement;
};

if (document.addEventListener){
    document.addEventListener('click', hilightElement, false);
} else if (document.attachEvent){
    document.attachEvent('onclick', hilightElement);
}

Listen for click events on the document object. You can then examine the event object to find out which element was clicked, and then alter its CSS border or outline as desired.

A very simple example, that doesn't try to account for cross browser compatibility problems would be:

document.addEventListener('click', function (e) {
        e.target.style.outline = "solid blue 1px";
});

Example for JQuery:

$('#myElement'/* Replace with asterisk if you want it to work for every element */).click
(
    function()
    {
        $(this).css('outline', '1px solid red');
    }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM