[英]Words highlight on mouse over
您是否知道突出單詞並添加onmouseover事件的最有效方法?
我有文字,我想制作一些單詞解釋字段,所以當用戶將光標放在單詞上時,我將AJAX稱為字典並顯示其意義。
我有兩個想法:1)在顯示文本之前,將每個單詞放到<span onmouseon="my_foo("word");">
wrapper。 例如:
<span onmouseon="my_foo("Hello");">Hello</span>
<span onmouseon="my_foo("world");">world</span>
但我認為這會嚴重超載頁面。
2)當用戶在一個區域內按住光標超過0.5秒時,我得到指針坐標,計算顯示的單詞(我不知道是否可能)並進行AJAX調用。
您認為更好,更容易編碼的內容是什么?
首先突出光標下的單詞然后顯示它的含義,檢查我的小提琴: http : //jsfiddle.net/shahe_masoyan/z7nkU/1/
HTML
<div>
<span>This text is a test text</span>
</div>
JavaScript的
$('div').each(function() {
var $this = $(this);
$this.html($this.text().replace(/\b(\w+)\b/g, "<span>$1</span>"));
});
$('div span').hover(
function() {
$(this).css('background-color','#ffff66');
alert(getTheMeaningOfTheWord($(this).html()));
},
function() {
$(this).css('background-color','');
}
);
function getTheMeaningOfTheWord(word){
return word+' = theMeaning';
}
我認為1很簡單,可以這樣做:
小提琴: http : //jsfiddle.net/9d227/
HTML
<div id="yourDiv" style="Display: none;">your Text Here</div>
<div id="yourActualDiv"></div>
JQuery的
var wordArray = $('#yourDiv').html().split(' ');
var totalString = "";
for(var i=0;i<wordArray.length;i++)
totalString += "<span>" + wordArray[i] + " </span>";
$('#yourActualDiv').html(totalString);
var ConcurrenyFlag = 0;
$('#yourActualDiv span').mouseover(
function()
{
if(ConcurrenyFlag == 0)
{
ConcurrenyFlag = 1;
// Your code here.
ConcurrenyFlag = 0;
}
}
)
這樣,您只需將文本放在yourDiv
。 javascript代碼將為您處理剩下的事情。
希望這對你有所幫助。
ConcurrenyFlag
將有助於減少客戶端的負載,因為一次只能運行一個代碼部分。
這樣的事情應該做一些接近你正在尋找的事情。
$('.addWordDictionary').html('<span>'+$('.addWordDictionary').html().replace(/ {1,}/g, '</span> <span>')+'</span>');
但是,正如你所說,它可能是客戶密集型的,特別是如果有很多文本。
您可以使用Lettering.js來解決此問題
簡化示例:
HTML:
<div class="w">"You will die of suffocation, in the icy cold of space"<div>
JS:
$(".w").lettering('words');
我做了這些東西: http : //jsfiddle.net/wared/eAq9k/ 。 需要textarea並通過點擊而不是懸停來工作。 有關getCaret()
更多詳細信息,請訪問: https : //stackoverflow.com/a/263796/1636522 。
<textarea readonly>Lorem ipsum</textarea>
textarea {
display: block;
width: 100%;
border: none;
resize: none;
outline: none;
margin: .5em 0;
}
$(function () {
var el = $('textarea'),
text = el.text();
el.click(function () {
var i = getCaret(this),
w = getWord(text, i);
$('p').text(i + ' : "' + w + '"');
});
// https://stackoverflow.com/a/995374/1636522
el[0].style.height = '1px';
el[0].style.height = 25 + el[0].scrollHeight + 'px';
});
function getWord(s, i) {
var r = /\s/g;
while (i && !r.test(s[--i])) {}
r.lastIndex = i && ++i;
return s.slice(i, (
r.exec(s) || { index: s.length }
).index);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.