开发者社区> 问答> 正文

通过点击突出显示一个单词

已解决

我发现了一个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的原始来源了

展开
收起
sossssss 2019-11-28 18:07:14 1567 0
1 条回答
写回答
取消 提交回答
  • 采纳回答

    第一次$("span").css("background-color", "");重置所有颜色在设置被单击元素的颜色之前:

    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");
    });
    
    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");
    });
    

    您也可以将单击的元素保存在变量中:

    您也可以将单击的元素保存在变量中: 您也可以将单击的元素保存在变量中:

    2019-11-28 18:10:18
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载