gpt4 book ai didi

javascript - 如何使用 ctrl + 单击选择多个单元格

转载 作者:行者123 更新时间:2023-12-01 14:46:02 25 4
gpt4 key购买 nike

我有一张带数字的 table 。当我单击表格中的单元格时,它会切换事件状态。我想选择一个单元格并按 crtl 并选择另一个单元格,结果第一个和第二个之间的单元格将变为事件状态。如何实现?

密码笔 https://codepen.io/geeny273/pen/GRJXBQP

<div id="grid">
<div class="cell">1</div>
<div class="cell">2</div>
<div class="cell">3</div>
<div class="cell">4</div>
<div class="cell">5</div>
<div class="cell">6</div>
</div>
const grid = document.getElementById("grid")

grid.onclick = (event) => {
event.stopPropagation();
const { className } = event.target;

if (className.includes('cell')) {
if (className.includes('active')) {
event.target.className = 'cell';
} else {
event.target.className = 'cell active';
}
}
}

它应该像类次突出显示一样工作,并且可以双向工作

最佳答案

尝试这个:

const cells = document.querySelectorAll(".cell");
let lastClicked;

function handleClick(e) {
// Toggle class active
if (e.target.classList.contains("active")) {
e.target.classList.remove("active");
} else {
e.target.classList.add("active");
}

// Check if CTRL key is down and if the clicked cell has aready class active
let inRange = false;
if (e.ctrlKey && this.classList.contains("active")) {
// loop over cells
cells.forEach(cell => {
// check for the first and last cell clicked
if (cell === this || cell === lastClicked) {
// reverse inRange
inRange = !inRange;
}
// If we are in range, add active class
if (inRange) {
cell.classList.add("active");
}
});
}
// Mark last clicked
lastClicked = this;
}

cells.forEach(cell => cell.addEventListener("click", handleClick));
#grid {
display: grid;
grid-template-columns: repeat(3, 50px);
grid-template-rows: repeat(2, 50px);
}

.cell {
display: flex;
justify-content: center;
align-items: center;
border: solid 1px #ccc;
}

.active {
background-color: #80aaff;
}
<div id="grid">
<div class="cell">1</div>
<div class="cell">2</div>
<div class="cell">3</div>
<div class="cell">4</div>
<div class="cell">5</div>
<div class="cell">6</div>
</div>


codepen

关于javascript - 如何使用 ctrl + 单击选择多个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60809845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com