获取可编辑div光标位置

要想得到那种所见及所得的网页编辑效果:即点击一下就可以编辑元素然后鼠标移到别处就算编辑完成

必须用div编辑而不是表单

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Div 光标位置 插入 文字 或 HTML</title>
<script language="javascript" type="text/javascript">
var pos;
    function getPos()
    {
        pos = document.selection.createRange();
    }

    function fn_insertPos()
    {     
        if(pos!=null)
        {
            pos.text="插入文字内容";
            //pos.pasteHTML("<font color='red'>文字内容</font>");
            //pos.pasteHTML("<br/>文本框控件:<input id='Text1' type='text' />");
            
            //释放位置
            pos=null;
        }
        else
        {
            alert("没有正确选择位置");
        }        
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
        <div id="myDiv" style="width: 300px; height: 100px; 
          border: black 1px solid; font-size:small; line-height:1; "
          onclick="getPos();"   onkeyup="getPos();"  contenteditable="true">
          一二三四五六七八</div>
        <input id="Button1" type="button" onclick="fn_insertPos();" 
         value="点击本按钮在Div中插入相关内容" />              
    </form>
</body>
</html>

你可能感兴趣的:(JavaScript,function,null,input,div,button)