简体   繁体   English

Javascript返回触发事件的元素的id

[英]Javascript return id of the element that triggert the event

I have a range of divs (projects) which have a display:none-ed overlay container inside of them, containing additional info. 我有一系列div(项目),它们内部有一个display:none-ed overlay容器,包含其他信息。
If the mouse enters the outer div, that overlay container should recieve another class making it visible. 如果鼠标进入外部div,则该覆盖容器应该接收另一个类使其可见。 On mouse leaving the class should be removed. 在鼠标离开时,应该删除该类。
I solved it using onmouseover="setactive('DIV ID')", but it made the code look pretty messed up so I tried to switch to Eventlisteners. 我使用onmouseover =“setactive('DIV ID')”来解决它,但它使代码看起来很混乱,所以我试图切换到Eventlisteners。 It won't work though and I can't figure out why. 它不会起作用,我无法弄清楚原因。 This is my script so far: 到目前为止这是我的脚本:

// Init Eventlisteners for each container

        window.addEventListener("load", start, false);
        function start() {
            var project_containers = document.getElementsByClassName('content-project')
            for (var i = 0; i < project_containers.length; i++) {
                project_containers[i].addEventListener("mouseover", setactive(), false)
                project_containers[i].addEventListener("mouseout", setinactive(), false)
            }
        }



// If mouse is over container, add overlay_active class

        function setactive() {
            var container = document.getElementById(event.currentTarget);
            var overlay_class = container.getElementsByClassName("element-overlay")[0];
            if (!(overlay_class.className.match(/(?:^|\s)overlay_active(?!\S)/))) {
                overlay_class.className += " overlay_active";
            }
        }



// If mouse is outside the container again, remove overlay_active class

        function setinactive() {
            var container = document.getElementById(event.currentTarget);
            var overlay_class= container.getElementsByClassName("element-overlay")[0];
            if (overlay_class.className.match(/(?:^|\s)overlay_active(?!\S)/)) {
                overlay_class.className = overlay_class.className.replace(/(?:^|\s)overlay_active(?!\S)/g, '')
            }
        }

You don't need the id to set container , your functions could be like this: 你不需要id来设置container ,你的功能可能是这样的:

function setinactive(e) {
    var container = e.currentTarget;
        //your code
    }
}

And then the call: 然后电话:

project_containers[i].addEventListener("mouseout", setinactive, false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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