我有一个网格,当选择一个项目时,我想为当前项目之前或之后的每一列添加不同的类。我想出了以下功能来做到这一点,但想知道是否有更简单,更简单的方法:
var items = document.querySelectorAll('.item');
var bodyWidth = 200;
var itemWidth = 50;
var itemsInRow = Math.floor(bodyWidth/itemWidth);
var activeItemIndexInRow;
var directionClass;
var otherItemIndexInRow;
var removeClasses = function(){
items.forEach(function (item, i) {
item.className = 'item';
});
}
items.forEach(function (selectedItem, selectedItemIndex) {
selectedItem.addEventListener('click', function(event) {
removeClasses();
activeItemIndexInRow = selectedItemIndex-Math.floor(selectedItemIndex/itemsInRow)*itemsInRow;
selectedItem.classList.add('active');
items.forEach(function (otherItem, otherItemIndex) {
otherItemIndexInRow = otherItemIndex-Math.floor(otherItemIndex/itemsInRow)*itemsInRow;
if(otherItemIndexInRow < activeItemIndexInRow) directionClass = 'green';
if(otherItemIndexInRow === activeItemIndexInRow) directionClass = 'red';
if(otherItemIndexInRow > activeItemIndexInRow) directionClass = 'blue';
otherItem.classList.add(directionClass);
});
});
});
&#13;
* {
margin:0;
padding:0;
}
#wrapper {
width: 400px;
}
.item {
width:25%;
background:gray;
text-align:center;
height:100px;
line-height:100px;
color:#fff;
font-size:30px;
float:left;
}
.item.green {background:green}
.item.red {background:red}
.item.blue {background:blue}
.item.active {background:black}
&#13;
<div id="wrapper">
<div class="item">1</div><div class="item">2</div><div class="item">3</div><div class="item">4</div><div class="item">5</div><div class="item">6</div><div class="item">7</div><div class="item">8</div><div class="item">9</div><div class="item">10</div>
</div>
&#13;
答案 0 :(得分:1)
这应该有用。
var items = document.querySelectorAll('.item');
var itemsInRow = 4;
items.forEach(function(selectedItem, selectedItemIndex) {
selectedItem.addEventListener('click', function(event) {
var directionClass;
selectedItem.classList.add('active');
var selectedCol = selectedItemIndex % itemsInRow;
items.forEach(function(otherItem, otherItemIndex) {
otherItem.className = 'item';
var otherCol = otherItemIndex % itemsInRow;
if (otherItemIndex === selectedItemIndex) directionClass = 'active';
else if (otherCol === selectedCol) {
directionClass = 'red';
} else {
directionClass = selectedCol < otherCol ? 'blue' : 'green'
}
otherItem.classList.add(directionClass);
});
});
});
&#13;
* {
margin: 0;
padding: 0;
}
#wrapper {
width: 400px;
}
.item {
width: 25%;
background: gray;
text-align: center;
height: 100px;
line-height: 100px;
color: #fff;
font-size: 30px;
float: left;
}
.item.green {
background: green
}
.item.red {
background: red
}
.item.blue {
background: blue
}
.item.active {
background: black
}
&#13;
<div id="wrapper">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
<div class="item">10</div>
</div>
&#13;