使用过滤器从数组中删除悬停的项目

时间:2019-02-05 13:15:32

标签: javascript arrays

我想向数组中的每个元素添加一个.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>

2 个答案:

答案 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')
        });
    });
});