Getting id of any tag when mouseover

前端 未结 3 1961
花落未央
花落未央 2020-12-16 06:28

does anyone know how i can get the id of any element when the mouse is over ?

I want to show a div (box) over the elements (tags) the mouse is over. I cannot modify

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 06:50

    You mean you want the target of the onmouseover event, so you can access the element's properties:

    
    

    Take a look at Event Properties for a cross-browser way to get the target (the following example is from the aforementioned website):

    function doSomething(e) {
        var targ;
        if (!e) var e = window.event;
        if (e.target) targ = e.target;
        else if (e.srcElement) targ = e.srcElement;
        if (targ.nodeType == 3) // defeat Safari bug
            targ = targ.parentNode;
    }
    

    So to put those together:

    document.onmouseover = function(e) {
        var targ;
        if (!e) var e = window.event;
        if (e.target) targ = e.target;
        else if (e.srcElement) targ = e.srcElement;
        if (targ.nodeType == 3) // defeat Safari bug
            targ = targ.parentNode;
        console.log(targ.id);
    }
    

提交回复
热议问题