你可能想看看一些现有的上下文菜单插件
- http://www.trendskitchens.co.nz/jquery/contextmenu/
- http://labs.abeautifulsite.net/projects/js/jquery/contextMenu/demo/
- http://plugins.jquery.com/plugin-tags/context-menu
为了获得在当前选定的词文本区域,看看fieldSelection插件。
因此,使用第二插件和fieldSelection(声明:我觉得关于字符串替换索引稍微偏离 - 还没有完全测试)
的Javascript
$(document).ready(function() {
//replace
$("#tx").contextMenu({
menu: 'replace'
}, function (action, el, pos) {
update(action, el)
});
function update(action, el) {
var range = $("#tx").getSelection();
var textLength = $("#tx").val().length;
var firstPart = $("#tx").val().substring(0, range.start);
var secondPart = $("#tx").val().substring(range.start, textLength);
var lastIndexofSpaceInfirstPart = firstPart.lastIndexOf(" ");
var firstIndexofSpaceInSecondPart = secondPart.indexOf(" ");
var startOfWord = 0
var endOfWord = 0
if (lastIndexofSpaceInfirstPart < 0) {
// start of string
startOfWord = 0;
} else {
startOfWord = lastIndexofSpaceInfirstPart;
}
if (firstIndexofSpaceInSecondPart < 0) {
// end of textArea
endOfWord = textLength
} else {
endOfWord = firstIndexofSpaceInSecondPart + range.start;
}
var word = $.trim($("#tx").val().substring(startOfWord, endOfWord));
var replaceMent = $("#tx").val().substr(0, startOfWord)
+ action.toString()
+ $("#tx").val().substr(endOfWord, textLength);
alert(
"rangeStart: " + range.start +
"\n\nrangeEnd: " + range.end +
"\n\nrangeLength: " + range.length +
+"\n\nfirstPart: " + firstPart
+ "\n\n secondPart: " + secondPart
+ "\n\n lastIndexofSpaceInfirstPart: " + lastIndexofSpaceInfirstPart
+ "\n\n firstIndexofSpaceInSecondPart:" + firstIndexofSpaceInSecondPart
+ "\n\nWordStart: " + startOfWord
+ "\n\nEndofWord: " + endOfWord
+ "\n\nWord: '" + word + "'"
+ "\n\nNew Text: '" + replaceMent + "'"
);
}
});
的Html
<textarea id="tx">
Some text
</textarea>
<ul id="replace" class="contextMenu">
<li class="edit"><a href="#youwordhere1">youwordhere1</a></li>
<li class="cut separator"><a href="#youwordhere2">youwordhere2</a></li>
<li class="copy"><a href="#youwordhere3">youwordhere3</a></li>
<li class="paste"><a href="#youwordhere4">youwordhere4</a></li>
<li class="delete"><a href="#youwordhere5">youwordhere5</a></li>
<li class="quit separator"><a href="#youwordhere6">youwordhere6</a></li>
</ul>
@ahmed非常感谢你的回应。我编辑了这个问题,以更清楚地解释问题。PLZ C如果你能帮我到那里 – 2010-11-05 17:56:26
@muhammed - 这正是上面的代码所做的。它获取鼠标光标下的当前单词。 – Ahmad 2010-11-05 18:51:05
@muhammed - 关于出现在上下文菜单中的单词的选择,我想这可能需要在呈现上下文菜单之前通过ajax进行更新。 – Ahmad 2010-11-05 19:05:22