2017-04-15 10 views
0

我試圖設置此Javascript: How to detect if a word is highlighted的變化,但我想運行函數getSelectedText只有當所選文本的值相匹配H1 ID當選定文本,如果等於值相同ID,運行功能

我設置看起來像代碼:

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; 

我包括警報( '嗨')如果循環裏面看到正在運行,只是爲了測試,但在我的測試中沒有證據,也沒有看到控制檯中的任何錯誤。整個代碼位於http://codepen.io/malditojavi/pen/LWmRvp?editors=1010

在這種情況下,只有在選擇了完整字符串'產品標題'時才能運行該函數,而不是HTML文檔中的任何其他文本。

回答

1

if應該是:

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

但似乎你的函數可以只返回一個boolean值,指示預期的文本進行匹配。正如你已經知道那種情況下的文字,只要返回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>

相關問題