日期:2014-05-17  浏览次数:20634 次

html focus 引入 类似微博的效果

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>无标题文档</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
    <label>
        <textarea name="test1" id="test1" cols="45" rows="5">这是默认内容,嘿嘿,测试一下!</textarea>
        <br/>
        <br/>
        <input name="tag" type="text" id="tag" value="AAA"/>
        <br/>
        <br/>
        <a href="javascript:void(0);"
           onclick="insertAtCursor(document.getElementById('test1'), document.getElementById('tag').value);">插入</a>
    </label>
</form>
</body>
</html>
<script type="text/javascript">
    function insertAtCursor(myField, myValue) {
        if (document.selection) {   //IE support
            myField.focus();
            sel = document.selection.createRange();
            sel.text = myValue;
            sel.select();
        }
        else if (myField.selectionStart || myField.selectionStart == '0') {  //mozilla/netscape support
            var startPos = myField.selectionStart;
            var endPos = myField.selectionEnd;
            var restoreTop = myField.scrollTop;  // save scrollTop before insert
            myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
            if (restoreTop > 0) {  // restore previous scrollTop
                myField.scrollTop = restoreTop;
            }
            myField.focus();
            myField.selectionStart = startPos + myValue.length;
            myField.selectionEnd = startPos + myValue.length;
        } else {
            myField.value += myValue;
            myField.focus();
        }
    }
</script>