我想向数组中的每个元素添加一个.inactive
类,但不包括触发了mouseover
事件的元素。我想使用filter
函数来执行此操作,但是,我不确定如何从.item
数组中“过滤”悬停的items
。当前,所有items
都将添加.inactive
类
const items = document.querySelectorAll('.item');
[...items].forEach(link => {
link.addEventListener('mouseover', function() {
console.log(link)
const inactives = [...items].filter(item => link)
inactives.forEach(inactive => {
inactive.classList.add('inactive')
});
});
link.addEventListener('mouseout', function() {
[...items].forEach(item => {
item.classList.remove('inactive')
});
});
});
.item.inactive {
opacity: 0.5;
}
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
<div class="item">Item 6</div>
<div class="item">Item 7</div>
答案 0 :(得分:2)
您必须通过与当前链接进行比较来修改过滤器:
const inactives = [...items].filter(item => item !== link)
我还将inactive
类添加到所有链接中以开始。
为简化起见,您可以简单地将inactive
类添加到mouseout
上的所有项目并将其删除到mouseover
上的悬停项目中。这样,您就无需过滤链接。
const items = document.querySelectorAll('.item');
[...items].forEach(link => {
link.classList.add('inactive');
link.addEventListener('mouseover', function() {
link.classList.remove('inactive');
});
link.addEventListener('mouseout', function() {
[...items].forEach(item => {
item.classList.add('inactive');
});
});
});
.item.inactive {
opacity: 0.5;
}
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
<div class="item">Item 6</div>
<div class="item">Item 7</div>
答案 1 :(得分:-1)
您的代码基本上是正确的。进行一些小的更改即可使用。
准备发表评论。
这里是一个例子。
@kotlinx.serialization.Serializable
data class Congregation(
var id: Int,
var name: String,
var language: String
)
render() {
return (
<div dangerouslySetInnerHTML={{ __html: '<p>This is dangerous</p>' }} />
);
}
const items = document.querySelectorAll('.item');
[...items].forEach(link => {
link.addEventListener('mouseover', function() {
const inactives = [...items].filter((item) => item != link) // return all items except the current item
link.classList.remove('inactive') // remove inactive from the current item
inactives.forEach(inactive => {
inactive.classList.add('inactive')
});
});
link.addEventListener('mouseout', function() {
[items].forEach(item => {
if (item.classList)
item.classList.remove('inactive')
});
});
});