首页 > 解决方案 > 通过单击突出显示一个单词

问题描述

我找到了一个 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 找到原始来源。

标签: javascriptjquery

解决方案


在设置被点击元素的颜色之前先调用$("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>


推荐阅读