鼠标悬停和鼠标移动时遇到一些问题
我想在用户将鼠标放在图像中时使用mouseover(id = calendrieragenda),但只有当他离开父div(id = divagenda)时才使用mouseout,但是当用户离开他时它不起作用鼠标从图像中,它激活功能mouseout
var divagenda = document.getElementById('divagenda');
var calendrieragenda = document.getElementById('imageagenda');
calendrieragenda.addEventListener('mouseover', function() {
document.getElementById('divagenda').className = 'popUpAgendaMouseOver';
});
divagenda.addEventListener('mouseout', function() {
document.getElementById('divagenda').className = 'popUpAgendaMouseOut';
});
#divagenda {
margin-top: 1em;
}
#imageagenda {
width: 8%;
position: relative;
right: 6%;
margin-top: 1em;
margin-bottom: 1em;
transition-duration: 0.5s;
transform: translateX(-50%);
left: 50%;
z-index: 600;
}
.popUpAgendaMouseOver {
border-radius : 1em;
border : 1px rgba(250, 250, 250, .8) solid;
background-color: #444444;
transition: 1s;
}
.popUpAgendaMouseOut {
border : none;
background-color:none;
transition: 1s;
}
<div id="divagenda">
<a href="link" title="Lien vers l'Agenda" target="_blank">
<img id="imageagenda" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRSf_HZLgiKNGwWv6V9Urtv3P2Sfo_Liw2dwOnq_oXg6-WInr_s" />
</a>
</div>
我会向你展示我的代码:https://jsfiddle.net/v7pkhymm/7/
非常感谢你,祝你有愉快的一天!
答案 0 :(得分:2)
你遇到的问题是你的事件正在从img起泡,所以div也会收到那个事件。
有几种方法可以防止这种情况发生。您可以在calendrieragenda级别添加一个事件监听器来stopPropagation:
calendrieragenda.addEventListener('mouseout', function(event) {
event.stopPropagation();
});
或者您可以检查divagenda事件监听器,事件的目标实际上是div:
divagenda.addEventListener('mouseout', function(event) {
if (event.target !== this) {
return;
}
document.getElementById('divagenda').className = 'popUpAgendaMouseOut';
});
我更喜欢第二种方法,因为它不会创建不必要的事件监听器。
答案 1 :(得分:2)
更好的方法是使用mouseleave
来避免泡沫。
classList
集合添加和删除类。divagenda
来避免重复的getElementById
来电。
var divagenda = document.getElementById('divagenda');
var calendrieragenda = document.getElementById('imageagenda');
calendrieragenda.addEventListener('mouseover', function() {
divagenda.classList.add('popUpAgendaMouseOver');
});
divagenda.addEventListener('mouseleave', function() {
this.classList.remove('popUpAgendaMouseOver');
this.classList.add('popUpAgendaMouseOut');
});
&#13;
#divagenda {
margin-top: 1em;
}
#imageagenda {
width: 8%;
position: relative;
right: 6%;
margin-top: 1em;
margin-bottom: 1em;
transition-duration: 0.5s;
transform: translateX(-50%);
left: 50%;
z-index: 600;
}
.popUpAgendaMouseOver {
border-radius : 1em;
border : 1px rgba(250, 250, 250, .8) solid;
background-color: #444444;
transition: 1s;
}
.popUpAgendaMouseOut {
border : none;
background-color:none;
transition: 1s;
}
&#13;
<div id="divagenda">
<a href="link" title="Lien vers l'Agenda" target="_blank">
<img id="imageagenda" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRSf_HZLgiKNGwWv6V9Urtv3P2Sfo_Liw2dwOnq_oXg6-WInr_s" />
</a>
</div>
&#13;