As tdammers mentions, handling all of the details of putting together a process to handle what you're suggesting has many nuances that may have to be addressed, depending on what you're doing.
The basics of what you're trying to do is:
- Wrap an element around the text you want to find the position for, ie, in the case of text, probably a
<span>
.
- Get either the
$.offset()
or $.position()
of the element or elements you added. Whichever you choose is relevant to what you're trying to do; the first is relevant to the document
, the second to the containing element.
I created a simple demo of a script to "highlight" a term typed into a textbox in several paragraphs using div
s with position: absolute
and top
/left
offsets relative to the terms found in the paragraphs (located by the <span>
surrounding them).
Note, this is only a demonstration (of $.offset()
); it's not production-ready code. There's a link to the live fiddle demo below the code snippets.
First, I created a function to find and create a highlight <div>
for each term found.
function highlightWordPositions(word) {
var $paras = $('p'),
$spans,
_top = 0,
_left = 0;
$paras.each(function(){
var $p = $(this),
regex = new RegExp(word, 'g');
$p.html($p.text().replace(regex, '<span>' + word + '</span>'));
$spans = $p.find('span');
$spans.each(function(){
var $span = $(this),
$offset = $span.offset(),
$overlay = $('<div class="overlay"/>');
$overlay
.offset($offset)
.css({
width: $span.innerWidth(),
height: $span.innerHeight()
}).show();
$(document.body).append($overlay);
});
});
}
Then, I attached a callback to the $.keyup()
event:
$('#term').keyup(function(event){
var term = this.value;
if (term == '') {
$('.overlay').remove();
return false;
} else if (term.indexOf(' ') != -1) {
this.value = term.replace(' ', '');
return false;
}
$('.overlay').remove();
highlightWordPositions(term);
});
http://jsfiddle.net/JaN75/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…