【问题标题】:When text selected, if equals same value as ID, run function选择文本时,如果与 ID 值相同,则运行函数
【发布时间】:2017-09-11 19:05:24
【问题描述】:

我正在尝试设置此 Javascript: How to detect if a word is highlighted 的变体,但我只想在所选文本与 h1 idgetSelectedText /strong>

我设置的代码如下:

  function getSelectedText() {
      var x = document.getElementById("titleProduct");
      var text = "";
      if (typeof window.getSelection === x) {
          alert('hey');
          text = window.getSelection().toString();
      } 
      return text;
  }

  function doSomethingWithSelectedText() {
      var selectedText = getSelectedText();
      if (selectedText) {
         document.getElementById("hiddenCTA").className = "visibleCTA";
      }
  }

  var x = document.getElementById("titleProduct");
  document.onmouseup = doSomethingWithSelectedText;

我在 if 循环中包含了 alert('hey') 以查看它正在运行,仅用于测试,但在我的测试中没有证据,我也看不到控制台中的任何错误。整个代码在http://codepen.io/malditojavi/pen/LWmRvp?editors=1010

在这种情况下,该函数仅应在选择完整字符串“您的产品标题”而不是 HTML 文档中的任何其他文本时运行。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您的if 应该是:

    if (window.getSelection().toString() === x.textContent) {
    

    但您的函数似乎只能返回一个布尔值,指示预期文本是否匹配。由于您已经知道这种情况下的文本,因此返回 true 或 false 就足够了。以下是我建议的写作方式:

    function isSelectedText(txt) {
        return window.getSelection().toString().trim() === txt;
    }
    
    function doSomethingWhenTextSelected() {
        if (isSelectedText(document.getElementById("titleProduct").textContent)) {
            document.getElementById("hiddenCTA").className = "visibleCTA";
        }
    }
    
    document.onmouseup = doSomethingWhenTextSelected;
    .hiddenCTA { display: none }
    .visibleCTA { display: block }
    <h3 id="titleProduct">Title Of Your Product</h3>
    
    hhhh
    
    <div class="hiddenCTA" id="hiddenCTA">Hey, we do price match!</div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多