我有一个按钮,该按钮使用带有window.find的功能来搜索/突出显示一个单词。
我面临的问题是我无法使此搜索区分大小写。而且,如果可能的话,我想在特定的div内进行搜索。
var myButton = document.getElementById('myButtonId');
myButton.addEventListener('click', function() {findString ('Text',1,0,0,0,0,0)});
function findString (str) {
if (parseInt(navigator.appVersion)<4) return;
var strFound;
if (window.find) {
strFound=self.find(str);
if (!strFound) {
strFound=self.find(str,0,1);
while (self.find(str,0,1)) continue;
}
}
if (!strFound) console.log ("String '"+str+"' not found!")
return;
}
<button id="myButtonId">Find</button>
<div id="myDivId1">
<p>
This is some text in a paragraph.<br>
It has Text placed in my first div.
</p>
</div>
<div id="myDivId2">
<p>
This is some texT in a paragraph.<br>
It has tExt placed in my second div.
</p>
</div>
答案 0 :(得分:1)
更新
中找到window.find
有一个属性aCaseSensitive
,我很想在
https://developer.mozilla.org/en-US/docs/Web/API/Window/find
因此,我在这里更新了您的代码,并使用了window.find(str,true),其中boolean表示aCaseSensitive
搜索操作。
var myButton = document.getElementById('myButtonId');
myButton.addEventListener('click', function() { findString ('Text',1,0,0,0,0,0)});
function findString (str) {
if (parseInt(navigator.appVersion)<4) return;
var strFound;
if (window.find) {
strFound=self.find(str, true);
if (!strFound) {
strFound=self.find(str,true,1);
while (self.find(str,true,1)) continue;
}
}
}
<button id="myButtonId">Find</button>
<div id="myDivId1">
<p>
This is some text in a paragraph.<br>
It has Text placed in my first div.
</p>
</div>
<div id="myDivId2">
<p>
This is some texT in a paragraph.<br>
It has tExt placed in my second div.
</p>
</div>
答案 1 :(得分:0)
我找到了用于getSelection的解决方案(stackoverflow.com/a/987376),并在下面的示例中进行了说明(如果有人需要)。
它将选择包含关键字的标签。
var myButton = document.getElementById('myButtonId');
myButton.addEventListener('click', () => selectText());
function selectText(node) {
var pSelect = document.querySelectorAll('p'), i;
for (i = 0; i < pSelect.length; ++i) {
if(pSelect[i].textContent.match('tExt')){
var node = pSelect[i];
}
}
if (window.getSelection) {
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(node);
selection.removeAllRanges();
selection.addRange(range);
} else {
console.warn("Unsupported browser.");
}
}
<h3>Button 'Find' selects the 'p' tag containing 'tExt'.</h3>
<button id="myButtonId">Find</button>
<div id="myDivId1">
<p>
This is some text in a paragraph.<br>
It has Text placed in my first div.
</p>
</div>
<div id="myDivId2">
<p>
This is some texT in a paragraph.<br>
It has tExt placed in my second div.
</p>
</div>