多个对象上的javascript eventlistener [英] javascript eventlistener on multiple objects
问题描述
我为几个< div>
元素制作了一个EventListener,现在,我想更改此特定元素的子元素的不透明度,以便在此特定元素上的EventListener为true时进行更改.如何使用jQuery或Javascript编写代码?我已经写了伪引用,我认为应该可以.我在将其翻译为js时遇到问题.
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>
推荐答案
对于事件监听器,您可以使用 this
引用当前元素.由于该处理程序仅在发生鼠标悬停事件时才会做出反应,因此您无需对其进行检查,因为它始终为true.
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;
}
然后,如果要清除鼠标输出时的样式更改,只需将相同的代码添加到mouseOut函数中即可.
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;
}
此外,如果您仅修改子元素的样式,则可以仅使用CSS来解决此问题.
Also, if you are only modifying the style of child elements, you could solve this with just css.
.overlay:hover img {
opacity: .8;
}
这篇关于多个对象上的javascript eventlistener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!