1. 程式人生 > >可編輯 DIV 相容 chrome,ie9-10,ie11改進

可編輯 DIV 相容 chrome,ie9-10,ie11改進

只為了相容一個IE11發火,兩天兩夜沒怎麼睡覺哭,一邊看著武則天祕史奮鬥,足足看了45集,可憐終於做出來了睡覺,誰設計的IE11,為什麼要改了改去,range,selection,documnent,getSelection(),w3c,js ,jquery1.4.1,IE11,不說了,程式碼奉上,感謝原作者ahjesus,不多說了,還有8集呢.

<!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">
<!--<meta http-equiv="X-UA-Compatible" content="IE=9" /> -->
<head>
    <title>js獲取div編輯框,textarea,input text的游標位置,相容FF和IE</title>
    <script src="C:/js/jquery-1.4.1.js" type="text/javascript"></script>
    <!--  <script src="C:/js/jquery-1.10.2.min.js" type="text/javascript"></script>   -->
    <script type="text/javascript">
        var pos=0;//游標初始位置
        //去除左右所有空格
        String.prototype.trim = function () {
            return this.replace(/(^\s*)|(\s*$)/g, "");
        }
        function getPosition(element) {
            debugger;
            var OsObject = "";
            if (navigator.userAgent.indexOf("MSIE") > 0) {
                OsObject = "MSIE";
            }
            if (navigator.userAgent.indexOf("Firefox") > 0) {
                OsObject = "Firefox";
            }
            if (navigator.userAgent.indexOf("Safari") > 0) {
                OsObject = "Safari";
            }
            if (navigator.userAgent.indexOf("Camino") > 0) {
                OsObject = "Camino";
            }
            //if (navigator.userAgent.indexOf("Gecko") > 0) {
            //    OsObject = "Gecko";
           // }
            if (navigator.userAgent.indexOf("Chrome") > 0) {
                OsObject = "Chrome";
            } 
            
            var result = 0;
            if (!document.selection ) { //非IE瀏覽器 IE11不支援document.selection 


                if (Object.hasOwnProperty.call(window, "ActiveXObject") && !window.ActiveXObject) {     // is IE11 wulongfei 2015-1120--2015-1122
                    var rng;
                    if ($(element).attr("tagName") == "TEXTAREA" || ($(element).attr("tagName") == "INPUT" && $(element).attr("type") == "text") || ($(element).attr("tagName") == "DIV" && $(element).attr("contenteditable") == "true")) {
                     element.focus();
                     var anchorNodeProp = window.getSelection().anchorNode; //當前節點
                     var currentIndex = window.getSelection().anchorOffset;//2015-11-20 ie11
                     var selectionnode = window.getSelection().focusNode;////測試 
                     var selection = window.getSelection().focusOffset;//測試   
                     var range2=document.getSelection().getRangeAt(0);//測試 


                     var isEnd=range2.endContainer.parentNode.nextSibling;


                     var preNode=anchorNodeProp.previousSibling;//前一個節點//測試 
                     var parentNode=anchorNodeProp.parentNode;//父節點//測試 
                     var anchlist=parentNode.childNodes;//測試 


                     //console.log(window.getSelection().anchorNode.textContent);
                    // console.log(window.getSelection().anchorNode.parentNode.textContent);
                    // console.log($(element).text());


                     //if(isEnd==null){
                     //       result=$(element).text().length;
                    // } else if (window.getSelection().anchorNode.textContent == $(element).text()) {//普通文字 點選在末尾
                                     //result = window.getSelection().anchorOffset;//廢棄
                    //     result=window.getSelection().anchorNode.parentNode.textContent.length;
                    // }else{
                     
                     //var anchorNodeProp = window.getSelection().anchorNode; //當前節點    
                     var range=document.getSelection().getRangeAt(0);
                    // var preNodeste=range.commonAncestorContainer.parentNode.previousSibling.wholeTest;


                    var txt = "";
                    // var txtoo = window.getSelection().anchorNode.previousSibling;
                    //var txtoo = range.startContainer.parentNode.previousSibling;//測試 有span
                    var txtoo = range.startContainer.previousSibling;
                   // var txtoo2 = range.endContainer.previousSibling;//測試 
                    var txt3 = "";//測試 
                    var txtoo3 = range.endContainer.parentNode.previousSibling;//測試 
                   // console.log(txtoo.textContent);
                   // console.log(txtoo2.textContent);
                    debugger;
                    //var txtoo=window.getSelection().focusNode.parentNode.previousSibling;//
                    while (txtoo != null) {
                        txt += txtoo.textContent;
                        txtoo = txtoo.previousSibling;
                        //txtoo3 = txtoo3.previousSibling;//測試 
                    } 
                    console.log(range.endContainer.parentNode.nodeName);
                    var t3nodeName=range.endContainer.parentNode.nodeName;
                    while (txtoo3 != null&&t3nodeName!='DIV') {
                        txt3 += txtoo3.textContent;
                        txtoo3 = txtoo3.previousSibling;
                        //txtoo3 = txtoo3.previousSibling;//測試 
                    } 
                    debugger;//測試 
                    if(t3nodeName!='DIV'){
                        result=txt3.length+currentIndex;//測試 
                    }else{
                        result=txt.length+currentIndex;//測試 
                    }
                     
                    // result = txt.length + currentIndex;//2015-11-20 ie11相容  
                   // }




                }else {
                         return 0;
                    } 


                }
                else{//非ie11     // is IE11 wulongfei 2015-1120--2015-1122
                var thisTagName = null;
                if ($(element).attr("tagName") != "TEXTAREA" && $(element).attr("tagName") != "INPUT") {
                    if ($(element).attr("tagName") == "DIV" && $(element).attr("contenteditable") == "true") {
                        thisTagName = window.getSelection().anchorNode.parentElement.tagName;                        
                    } //出自http://www.cnblogs.com/ahjesus 尊重作者辛苦勞動成果,轉載請註明出處,謝謝!
                    else {
                        thisTagName == null;
                    }
                }
                else {                    
                    if ($(element).attr("tagName") == "INPUT" && $(element).attr("type") == "text") {
                        thisTagName = window.getSelection().anchorNode.tagName;
                    }
                    else {
                        console.log(window.getSelection());                     
                        thisTagName = window.getSelection().anchorNode.tagName;
                    }
                }
                console.log(thisTagName);
                if (thisTagName == "TEXTAREA" || thisTagName == "INPUT" || (thisTagName=="BODY"&&OsObject == "Chrome")) {
                    result = element.selectionStart
                } //出自http://www.cnblogs.com/ahjesus 尊重作者辛苦勞動成果,轉載請註明出處,謝謝!                
                else if (thisTagName != null) {
                    if (thisTagName == element.tagName) {
                        if (window.getSelection().anchorNode.textContent == $(element).text()) {
                            result = window.getSelection().anchorOffset;
                        }
                        else {
                            var currentIndex = window.getSelection().anchorOffset;
                            var txt = "";
                            var txtoo = window.getSelection().anchorNode.previousSibling;
                            while (txtoo != null) {
                                txt += txtoo.textContent;
                                txtoo = txtoo.previousSibling;
                            } //出自http://www.cnblogs.com/ahjesus 尊重作者辛苦勞動成果,轉載請註明出處,謝謝!
                            result = txt.length + currentIndex;
                        }
                    }
                    else {
                        var currentIndex = window.getSelection().anchorOffset;
                        var txt = "";
                        var txtoo = window.getSelection().anchorNode.parentElement.previousSibling;
                        while (txtoo != null) {
                            txt += txtoo.textContent;
                            txtoo = txtoo.previousSibling;
                        }
                        result = txt.length + currentIndex;
                    }
                } //出自http://www.cnblogs.com/ahjesus 尊重作者辛苦勞動成果,轉載請註明出處,謝謝!
                else {
                    return 0;
                }
              }//非ie11  
            } else { //IE
                var rng;
                if ($(element).attr("tagName") == "TEXTAREA" || ($(element).attr("tagName") == "INPUT" && $(element).attr("type") == "text") || ($(element).attr("tagName") == "DIV" && $(element).attr("contenteditable") == "true")) {
                    element.focus();
                    rng = document.selection.createRange();
                   //rng = window.getSelection();
                   rng.moveStart('character', -element.innerText.length);
                    var text = rng.text;
                    for (var i = 0; i < element.innerText.length; i++) {
                        if (element.innerText.substring(0, i + 1) == text.substring(text.length - i - 1, text.length)) {
                            result = i + 1;
                        }
                    }
                } //出自http://www.cnblogs.com/ahjesus 尊重作者辛苦勞動成果,轉載請註明出處,謝謝!
                else {
                    return 0;
                }
            }
            return result;
        }
        function getValue(aaa) {//獲得游標位置
            pos = getPosition(aaa);
            //alert(pos);
            document.getElementById("pnum").value = pos;
        }
        function changeSelectVer(aaa,value){
            debugger;
               // var value2="<span style='color:red;'>"+"${"+value+"}"+"</span>";
               var value2="${"+value+"}";
                //alert(value2);
                var str1=$("#Div1").text();//獲取簡訊腳本里的文字  不包括標籤
                //alert(str1);
                var fx1=str1.substring(0,pos);
                var fx2=str1.substring(pos,str1.length);
                var str2=fx1+value2+fx2;
                //alert(str2);
                console.log(str2);
                var str3='';
                if(str2.indexOf("$")>=0){
                    //1.根據$進行分割
                    var stringarray=[];
                    stringarray=str2.split("$");
                    
                    for(var j=0;j<stringarray.length;j++){
                       // alert(stringarray[j]);
                        //2.進行正則替換
                        var reg1=new RegExp(/[\({][a-zA-Z]*[\})]/);
                        var strg1=stringarray[j];
                        var ms=strg1.match(reg1);
                        var we="<span style='color:red;'>"+"$"+ms+"</span>";
                        var strg2=strg1.replace(ms,we);
                        str3=str3+strg2;
                    }
                   
                   // alert(str2.length);//z作為文字長度記錄  不包括$
                    //alert(reg1.test(str2));
                    //match=reg1.exec(str2); 
                   // var reg1=new RegExp(/[\({][a-zA-Z]*[\})]/ig);  //ig表示採集陣列
                     //var arrMactches =[];
                    // arrMactches = str2.match(reg1);
                    //for (var i=0;i < arrMactches.length;i++){
                        //alert(arrMactches[i]); 
                      //  var ms=arrMactches[i];
                       // var we="<span style='color:red;'>"+ms+"</span>";                       
                       // str2=str2.replace(ms,we);
                   // }
                }
                     //alert(str2);
                $("#Div1").html(str3);    
                $("#myVerStr").val('');
               


        }
    </script>
    <style type="text/css">
        #Div1, #Div2
        {
            width: 500px;
            height: 100px;
            border: solid 1px black;
        }
    </style>
</head>
<body>
    <input id="pnum" type="text" value="Hello,wellcome to test! 你好,歡迎測試!" onmouseup="getValue(this)"
        style="display: block" />
    <div style='width:400px;height:100px'>
        <select id='myVerStr' name='verstr' onchange="changeSelectVer(this,this.value)" style="width:100%;height:20%;">
            <option value="">請單擊新增</option>
            <option value="Name">姓名Name</option>
            <option value="Age">年齡Age</option>
            <option value="Amount">金額Amount</option>
            <option value="Per">次數Per</option>
        </select>
    </div>




    <div id="Div1" onclick="getValue(this);" onkeyup="getValue(this);" contenteditable="true" style="word-break:break-all;width:600px;height:200px;">一二三<span>四五</span>六七八<span>九零</span> 注意原始碼開閉合標記之間不能換行,否則統計錯誤!注意div編輯框原始碼裡面是巢狀有其他標籤的,可以正常返回正確位置!</div>
    <br />
    <!--<div id="Div2" onclick="getValue(this);" onkeyup="getValue(this);">一二三四五六<span>七八</span></div>-->
</body>
</html>