js实现选中
选中文本内容
使用 window.getSelection() 方法获取当前选中的文本内容。该方法返回一个 Selection 对象,可以进一步操作选中的文本。
const selection = window.getSelection();
const selectedText = selection.toString();
console.log(selectedText); // 输出选中的文本内容
选中DOM元素
通过 document.querySelector() 或 document.getElementById() 等方法选中DOM元素。
const element = document.getElementById('myElement');
element.style.backgroundColor = 'yellow'; // 高亮选中的元素
选中复选框或单选按钮
使用 checked 属性来选中或取消选中复选框和单选按钮。
const checkbox = document.getElementById('myCheckbox');
checkbox.checked = true; // 选中复选框
选中下拉框选项
通过设置 selectedIndex 或直接操作 option 元素的 selected 属性来选中下拉框的选项。

const select = document.getElementById('mySelect');
select.selectedIndex = 2; // 选中第三个选项
// 或者
const option = document.querySelector('#mySelect option[value="optionValue"]');
option.selected = true;
选中文件输入
通过触发文件输入元素的 click 事件来模拟用户选择文件。
const fileInput = document.getElementById('fileInput');
fileInput.click(); // 打开文件选择对话框
选中文本输入框内容
使用 select() 方法选中文本输入框中的全部内容。
const textInput = document.getElementById('textInput');
textInput.select(); // 选中输入框中的全部文本
选中范围(Range)
通过 document.createRange() 创建一个范围,并设置其起点和终点来选中特定文本。

const range = document.createRange();
const startNode = document.getElementById('startNode');
const endNode = document.getElementById('endNode');
range.setStart(startNode, 0);
range.setEnd(endNode, 2);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
选中表格行或列
通过遍历表格的行或列,设置选中状态。
const table = document.getElementById('myTable');
const rows = table.getElementsByTagName('tr');
rows[1].style.backgroundColor = 'lightblue'; // 选中第二行
选中SVG元素
使用SVG的DOM方法选中SVG元素。
const svgElement = document.getElementById('mySvg');
const path = svgElement.querySelector('path');
path.setAttribute('fill', 'red'); // 选中并修改路径颜色
选中Canvas中的内容
通过Canvas的API选中并操作绘制的内容。
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 50, 50); // 选中并绘制一个矩形
以上方法覆盖了常见的选中操作场景,可根据具体需求选择合适的方式。






