【发布时间】: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