I looked all over for a code that will that would highlight a piece of text when I hover (or click) another text.
For instance if I have the text 'Je suis ici. I am here', when i hover the word 'here' I will have a yellow bachground for the word 'here' and for the word 'ici'. So I can show that the word here is the english corespondent for the french word 'ici'.
Someth开发者_如何学Going like google translator uses: http://translate.google.com/
Thanks in advance for any suggestions! Dana.
The way that Google Translate does it, is to split up each word in a sentence into separate <span>
tags with matching classes. These are then accessible via the DOM in JavaScript - most easily by using a framework such as JQuery.
For example, you could attach a mouseover()
function to highlight the currently hovered word.
I can't give you a full example here - you'll need to come up with a starting point and develop your solution from there.
This uses the jquery library and is borrowed heavily from this answer on SO to a related question.
What it does is break up each word in a paragraph tag (<p>
) and wrap it with a <span>
tag with a class of highlightable
and then attach an event on hover to the <span class='highlightable'>
tags. If you want only one paragraph to be used, then give it an ID and bind only to those items in that given ID. If a few paragraphs, use a class or multiple IDs.
<p>Each word will be wrapped in a span.</p>
<p>A second paragraph here.</p>
<script type="text/javascript">
$(document).ready(function() {
// wrap words in spans
$("p").each(function() {
$(this).text().
replace(/\b(\w+)\b/g, "<span class='highlightable'>$1</span>");
});
// bind to each highlightable span
$('.highlightable').hover(
function() { $(this).css('background-color','#ffff66'); },
function() { $(this).css('background-color',''); }
);
});
</script>
精彩评论