【问题标题】:how to highlight text and label it on runtime using javascript and html如何使用 javascript 和 html 在运行时突出显示文本并标记它
【发布时间】:2019-07-25 09:16:20
【问题描述】:

下面是我的代码。我想突出显示mouseup 上的文本。我是网络新手。我不知道为什么我的代码不起作用。它没有突出显示任何文本。

有人可以帮我找出问题吗?我写的代码大部分是我从网上到处复制的。

问题 2:一旦突出显示文本,我想通过鼠标右键单击打开一个菜单,其中包含 4 到 5 个选项,然后选择其中一个来标记突出显示的文本。稍后下载JSON格式的标注数据。

首先,我想解决我的第一个问题。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <title>TEST</title>

  
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
  <style>
    .red {
      color: red;
    }
    
    ;
  </style>


  <script>
    thisRespondHightlightText(".select--highlight--active");


    function thisRespondHightlightText(thisDiv) {
      $(thisDiv).on("mouseup", function() {
        var selectedText = getSelectionText();
        var selectedTextRegExp = new RegExp(selectedText, "g");
        var text = $(this).text().replace(selectedTextRegExp, "<span class='red'>" + selectedText + "</span>");
        $(this).html(text);
      });
    }

    function getSelectionText() {
      var text = "";
      if (window.getSelection) {
        text = window.getSelection().toString();
      } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
      }
      return text;
    }
  </script>
</head>

<body>

  <div class="select--highlight--active">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>

</body>

</html>

【问题讨论】:

  • 你期待像hoover这样的东西
  • 1.突出显示用户使用鼠标选择的文本。 2.标记突出显示的文本,右键单击>弹出菜单>暂时选择值,我共享的代码是1,当我运行我的代码时它不会突出显示文本
  • @irumzahra 请你看看我的回答,当用户选择文本时,它会以红色突出显示(只有选定的文本)我认为这就是你想要的
  • 是的,我接受了。成功了!

标签: javascript jquery html css web


【解决方案1】:

改变这个,Jquery需要先准备好

  $(function() {
        thisRespondHightlightText(".select--highlight--active");
   });

【讨论】:

  • 请投反对票的人解释为什么?它适用于 OP 的原始请求
  • 你现在能帮我解决我的第二个问题吗?
  • @irumzahra 我会看看,但如果你想在右键单击时打开一个新菜单,这确实有点工作
  • 如果你先得到相关插件sitepoint.com/right-click-context-menu-plugins然后看看你能走多远
  • @NipunTharuksha 首先批准编辑的定义是“批准明显改善帖子的编辑”它不会改善帖子。
猜你喜欢
  • 1970-01-01
  • 2022-11-13
  • 2012-01-28
  • 2012-03-28
  • 1970-01-01
  • 1970-01-01
  • 2018-10-20
  • 2016-10-29
  • 2015-01-08
相关资源
最近更新 更多