html - 检测 html 容器中突出显示的文本
问题描述
如何检测用户在非输入/文本区域元素中突出显示的文本?我正在渲染一个跨度内的字符数组,并希望能够检测到用户突出显示了哪些元素。但是,我看不到任何可以让我执行此操作的 ref 属性。
https://codesandbox.io/s/nervous-sound-rk3mf
import React from "react";
const values = ["a", "b", "c", "d", "e"]
const textRef = React.createRef();
export default function App() {
return (
<div ref = {textRef}>
{values.map(val => <var> {val} </var>)}
</div>
);
}
解决方案
您必须绑定一个单击事件才能突出显示该元素:
import React from "react";
const values = ["a", "b", "c", "d", "e"];
const textRef = React.createRef();
export default function App() {
// bind this event to the element
const checkText = e => {
console.log(`Hilighted item is: "${e.currentTarget.textContent}".`);
};
return (
<div ref={textRef}>
{values.map((val, i) => (
<var key={i} onClick={checkText}> //<-----here is the bound event
{" "}{val}{" "}
</var>
))}
</div>
);
}
推荐阅读
- jenkins - 用于 Jenkins 持续集成服务器的作业特定 SVN 签出文件夹
- python - 从 dict.items() 中获取值
- html - 如何使用 flexbox 将列表定位在中心?
- java - 如何在 IntelliJ 中使用不同的项目名称导入不同版本的 Maven 项目
- ruby - 如何使用 Selenium WebDriver 在嵌套 div 中查找元素
- mysql - 即使存在也无法删除密钥:错误代码:1091
- r - 如何从与 R 中的 df 列中的名称不匹配的文件夹中删除某些文件
- javascript - 使用纯 javascript 或 es6 从 json 文件导入数据
- ruby-on-rails - 如何在 Rails 中调试 FactoryGirl.create 回调错误?
- android - 通过 ADB 关闭特定应用程序的自动更新?