问题
I made an EventListener for a few <div>
elements, now i want do change the opacity on a child of this specific element to change if the EventListener is true on this specific element. How do I write that with jQuery or Javascript? I already wrote the pseudoquote, which I think should work. I have a problem to translate it to js.
var overLay = document.getElementsByClassName("overlay");
for (i = 0; i < overLay.length; i++) {
overLay[i].addEventListener("mouseover", mouseOver);
overLay[i].addEventListener("mouseout", mouseOut);
}
function mouseOver() {
document.getElementById("project_07").style.maxWidth = "20px"; //just for testing works!
/* PSEUDOCODE
if overlay[i] (mouseover === true) {
getChildElement of (this/ overlay[i]) // is an <img> element
and .style.opacity = ".8";
*/
}
function mouseOut() {
document.getElementById("project_07").style.maxWidth = "100%";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
回答1:
With event listeners, you can use this
to reference the current element. Because the handler will only react when during a mouseover event, you don't need to check it because it will always be true.
function mouseOver() {
this.querySelector("img").style.opacity = 0.8;
}
Then, if you want to clear the style change on mouseout, just add the same code to your mouseOut function.
function mouseOut() {
this.querySelector("img").style.opacity = 1;
}
Also, if you are only modifying the style of child elements, you could solve this with just css.
.overlay:hover img {
opacity: .8;
}
回答2:
When event is fired you can access the event prameters. It goes to function as n attribute.
One of properties of the event is target - element that fireв event.
function mouseOver(e) {
e.target.querySelector('img').style.maxWidth = "20px";
}
Try to console.dir(e.target) and research it.
回答3:
I will simply suggest: 1.assign class to all divs you want to have child change opacity let's say myClass
$('.myClass').children().on('mouseenter', function(){
$(this).css('opacity', '0.8');
});
来源:https://stackoverflow.com/questions/44037161/javascript-eventlistener-on-multiple-objects