我需要在html页面上使用一个非常简单的Javascript,它将执行以下操作..
显示如下文字:
This is a string of text and can be long
然后,如果您使用鼠标标记某些文本,则应插入所选文本并自动更新为文本字段
我该怎么做?
答案 0 :(得分:1)
创建只读textarea(您可以使用CSS将其装饰为简单的文本块)。然后处理它的onSelect事件到进动选择。你会得到类似的东西:
<script language="JavaScript">
function display(txtarea)
{
var sl = (txtarea.value).substring(txtarea.selectionStart, txtarea.selectionEnd);
alert (sl);
}
</script>
<textarea name="entry" onSelect="display(this);">Some text.</textarea>
答案 1 :(得分:0)
<script type="text/javascript">
function render(element)
{
var stext = element.value.substring(element.selectionStart, element.selectionEnd);
document.getElementById('selText').value = stext;
}
</script>
<input id="selText" value="" />
<textarea name="entry" onclick="render(this);">This is a string of text and can be long
</textarea>
希望这有帮助
答案 2 :(得分:0)
使用jQuery Based on this link
解决方案<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
var textSelected = function(el, elResult) {
var len = el.val().length;
var textarea = document.getElementById(el.attr("id"));
if($.browser.msie) {
if (document.selection) {
var range = document.selection.createRange();
var stored_range = range.duplicate();
stored_range.moveToElementText(textarea);
stored_range.setEndPoint('EndToEnd', range);
textarea.selectionStart = stored_range.text.length - range.text.length;
textarea.selectionEnd = textarea.selectionStart + range.text.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
}
} else {
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
}
var sel = textarea.value.substring(start, end);
if (sel.length!=0)
elResult.val(sel);
};
$("#text-entry").bind("select", function(){
textSelected($(this), $("#select-text"));
});
});
</script>
</head>
<body>
<input id="select-text" type="text" /><br />
<textarea id="text-entry">text for select</textarea>
</body>
</html>