javascript - 如何用鼠标选择范围单元格?
问题描述
我正在用 reactjs 建一个表。所以我想当用户单击一个单元格并按住移动到另一个单元格时。之间的单元格必须突出显示。我用 DOM 选择器来做。而且我认为这不是正确的反应方式。那么我如何在没有 DOM SELECTOR 的情况下做到这一点
这是我的 dom 选择代码:
import React, {useState} from "react";
import './Style.css';
export default function Table() {
const [cell, setCell] = useState([]);
let div = [];
let selecting, start, end;
let beginSelection = i => {
selecting = true;
start = i;
updateSelection(i);
};
let endSelection = (i = end) => {
selecting = false;
updateSelection(i);
};
let updateSelection = i => {
if (selecting)
end = i;
[...document.querySelectorAll('span')].forEach((span, i) =>
span.classList.toggle('selected', i >= start && i <= end || i >= end && i <= start));
};
for(let i = 0; i < 31; i++) {
let a = <span key={i} onMouseDown={()=>beginSelection(i)} onMouseUp={()=>endSelection(i)} onMouseMove={()=>updateSelection(i)}>{i}</span>;
div.push(a);
cell.push(a);
}
return div;
}
这是我的演示:https ://codesandbox.io/s/github/Kalipts/hover 请帮忙。谢谢
解决方案
using state & className for cell element
className={
(end <= i && i <= start) || (start <= i && i <= end) ? "selected" : ""
}
推荐阅读
- python - Python:字符串格式化和枚举?(以 Python 方式生成一个很好的多项式字符串表示)
- python - 有人可以解释一下为什么这个语句给出的输出为 'A', print (('A','B')[a == False]) 。a 的初始值 = True
- html - 如何创建具有线性渐变的动画圆形进度条?
- node.js - Faunadb:从子数据库创建文档到集合
- java - 如何使用 Java 发送 SOAP 请求?
- java - 使用ComponentScan其他包部署spring boot war文件到tomcat
- excel - 过滤行一起引用列中的值
- svelte - 为什么我不能在此 Svelte 应用程序的组件中保留与组件相关的操作?
- fortran - fortran中幂函数的效率
- html - 如何在表上使用引导表类 .table-hover 和 .table-striped