javascript - 通过单击突出显示一个单词
问题描述
我找到了一个 JQuery 脚本,它允许您通过单击来突出显示文本中的单词。
无论如何,是否可以调整只能通过单击突出显示一个单词的代码?因此,如果用户点击第二个词,第一个颜色编码的词将恢复正常。
var words = $( "p" ).first().text().split( /\s+/ );
var text = words.join( "</span> <span>" );
$( "p" ).first().html( "<span>" + text + "</span>" );
$( "span" ).on( "click", function() {
$( this ).css( "background-color", "red" );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Click a word in the paragraph and highlight it.</title>
</head>
<body>
<p>
This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission.
</p>
</body>
</html>
不幸的是,我无法再从 stackoverflow 找到原始来源。
解决方案
在设置被点击元素的颜色之前先调用$("span").css("background-color", "");
重置所有s的颜色:<span>
var words = $("p").first().text().split(/\s+/);
var text = words.join("</span> <span>");
$("p").first().html("<span>" + text + "</span>");
$("span").on("click", function() {
$("span").css("background-color", "");
$(this).css("background-color", "red");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission.
</p>
您还可以将单击的元素保存在变量中:
var words = $("p").first().text().split(/\s+/);
var text = words.join("</span> <span>");
$("p").first().html("<span>" + text + "</span>");
let highlighted;
$("span").on("click", function() {
$(highlighted).css("background-color", "");
$(this).css("background-color", "red");
highlighted = this;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission.
</p>
推荐阅读
- reactjs - 在 react-native 中链接和使用本地 UI 模块
- c - 寻找字谜
- c - 使用 Arduino IDE 为 I2C 光传感器创建回调函数
- ubuntu - 高 CPU 使用率 - 使用 VirtualBox 的 VM 非常慢
- flowtype - 类型声明中的扩展运算符在 Flow 中的作用是什么?
- python-3.x - Python print 语句返回语法错误
- python - 将 MatPlotLib 图插入 QWidget 类型
- groovy - 如何将 picocli groovy-grape 脚本转换为本机独立应用程序?
- asp.net-web-api - JWT 密码验证最佳实践建议
- python - 删除 HTML 文件中的换行符