我有一系列div(项目),里面有一个display:none-ed overlay容器,里面有附加信息。
如果鼠标进入外部div,则该覆盖容器应该接收另一个类使其可见。在鼠标离开时,应该删除课程
我使用onmouseover =“setactive('DIV ID')”来解决它,但它使代码看起来很混乱,所以我试图切换到Eventlisteners。它不会起作用,我无法弄清楚原因。
到目前为止,这是我的脚本:
// 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, '')
}
}
答案 0 :(得分:2)
您不需要设置container
的ID,您的功能可能是这样的:
function setinactive(e) {
var container = e.currentTarget;
//your code
}
}
然后是电话:
project_containers[i].addEventListener("mouseout", setinactive, false);