例如我有这样的HTML:
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
...
现在用javascript我怎么知道我正在徘徊的whic类,或者我如何让我的类徘徊。 我知道他们在javascript中显示为一个数组,我一直在使用:
var myElement = document.getElementsByClassName['class'][0/1/2];
所以我的需求是这样的:
myElement.onmouseover = function () {//code}
答案 0 :(得分:0)
const getClass = (ev) => { // ev is the mouseenter Event
const cls = ev.target.className // ev.target is the mouseentered Elem.
console.log( cls );
};
const item = document.querySelectorAll(".item"); // Get all your .item Elements
[...item].forEach( el => { // Every one of them...
el.addEventListener("mouseenter", getClass); // Assign a mouseenter Event callback
});
&#13;
<div class='item i1'>HOVER ME</div>
<div class='item i1'>HOVER ME</div>
<div class='item i2'>HOVER ME</div>
<div class='item i2'>HOVER ME</div>
&#13;
答案 1 :(得分:0)
您可以使用e.target
或e.currentTarget
document.querySelector('.item').forEach(function (item) {
item.onmouseover = function (e) {
// If you want myElement
console.log(e.currentTarget.className)
// If you want the element onto which the event occurred
console.log(e.target.className)
}
}
答案 2 :(得分:-1)
这应该有用。
const items = document.getElementsByClassName('item');
for(let i=0; i < items.length; i++){
items[i].addEventListener('mouseover', (e)=> {
console.log(e.target.className);
})
}
&#13;
.item {
border:1px solid black;
width: 100px;
margin-bottom: 10px;
}
&#13;
<div class='item red'>Red</div>
<div class='item yellow'>Yellow</div>
<div class='item blue'>Blue</div>
<div class='item green'>Green</div>
&#13;