获得容器里的被选择文本内容(兼容firefox,opera,ie)
本文按署名·非商业用途·保持一致授权作者:
,发表于2005年11月04日22时28分
<script type="text/javascript">
<!--
function getFieldSelection(select_field)
{
word='';
if (document.selection) {
var sel = document.selection.createRange();
if (sel.text.length > 0) {
word = sel.text;
}
}
else if (select_field.selectionStart || select_field.selectionStart == '0') {
var startP = select_field.selectionStart;
var endP = select_field.selectionEnd;
if (startP != endP) {
word = select_field.value.substring(startP, endP);
}
}
return word;
}
//-->
</script>
<textarea id="t_field" rows="3" cols="20"></textarea><br />
<span onmousedown="alert(getFieldSelection(document.getElementById('t_field')))" style="color:#6633FF;cursor:pointer">(Span_onmousedown)</span>
<span onclick="alert(getFieldSelection(document.getElementById('t_field')))" style="color:#6633FF;cursor:pointer">(Span_onclick)</span>
<button onclick="alert(getFieldSelection(document.getElementById('t_field')))">button_click</button>(Span_onmousedown) (Span_onclick)
注:当在IE里使用非按钮的元素onclick触发事件的时候,会得不到结果。因为在IE里,当一个非按钮元素被click,整个页面中的选择内容将会被改变。而在firefox,opera下就不存在这个问题。所以上面的(Span_onclick)在IE下将不可用

2005-11-07 20:46:36
不在文本框内选择点按钮怎么办呢
2005-11-09 02:07:47
神仙好啊。经常见你活跃在PHP社区。
不在文本框,可看这里。
http://joemaller.com/2005/04/24/post503/getselection-workaround