1. 程式人生 > >js生成div並在指定位置顯示出來

js生成div並在指定位置顯示出來

在這裡插入圖片描述
點選客戶名稱輸入內容 ,觸發post請求向後臺請求資料(模糊查詢)。然後將請求後的資料 生成一個div 在該輸入框下方顯示出來。下面是具體實現方法;
js:
建立請求

//建立請求
function createXMLHttpRequest() {
    xmlHttp = false;
    if (window.XMLHttpRequest) {        //for Mozilla
        xmlHttp = new XMLHttpRequest();
        if (xmlHttp.overrideMimeType) {
            xmlHttp.overrideMimeType("text/xml");
        }
    }
    else if (window.ActiveXObject) {   //for IE
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) { }
        }
    }

    if (xmlHttp == undefined || xmlHttp == null) {
        alert("XMLHttpRequest物件建立失敗!!");
    } else {
        this.xmlhttp = xmlHttp;
    }
}

獲取查詢結果(輸入框裡的內容,每隔500ms 提交一次)

function getSearchResult(queryurl, tbname, hfnameid, iflag, btngetinfo, event) {
    txtname = tbname;
    txtnameid = hfnameid;
    btntgetinfo = btngetinfo;
    runcount = runcount + 1;
    var tempscreen = screenval;
    screenval = escape($(txtname).value);
    var tempcount = runcount; //過濾500毫秒內的重複提交,重複不提交,空值不提交
    setTimeout(function () {
        if (event.keyCode != 38 && event.keyCode != 40 && event.keyCode != 32 && event.keyCode != 9 && event.keyCode != 13 && (tempcount == runcount && tempscreen != screenval && screenval.length > 0 && runcount != 1)) {
            runcount = 0;   //允許提交後重置執行標識
            createXMLHttpRequest(); //初始化XMLHttpRequest物件
            if (!xmlHttp) {
                window.alert("Cannot create XMLHttpRequest instance!");
                return false;
            }
            var parmurl = "keydata=" + escape($(txtname).value);    //建立請求的URL
            if (iflag == 1) { parmurl += "&f=1"; }
            xmlHttp.onreadystatechange = callback;      //設定處理響應的回撥函式
            xmlHttp.open("POST", queryurl, true);        //開啟與伺服器的連線,使用post方式            
            xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;"); //post需要設定請求表頭            
            xmlHttp.send(parmurl);  //傳送請求並設定引數,引數的設定為param=value的形式
        }
        else {            
            //alert(tempcount + "," + runcount + "," + tempscreen + "," + screenval + "," + screenval.length);
        }
    }, 500)
    if (screenval.length < 1) {
        MoveDivTableBlur();
    }
}

回撥函式 返回查詢的資訊

//返回查詢資訊
function callback() {
    //響應完成且響應正常
    //  if(objXMLHttp.readyState == 1){
    //      alert("XMLHttpRequest物件開始傳送請求");
    //  }else if(objXMLHttp.readyState == 2){
    //      alert("XMLHttpRequest物件的請求傳送完成");
    //  }else if(objXMLHttp.readyState == 3){
    //      alert("XMLHttpRequest物件開始讀取伺服器的響應");
    //  }else if(objXMLHttp.readyState == 4){
    //      alert("XMLHttpRequest物件讀取伺服器響應結束");
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            //資訊已經成功返回,開始處理資訊
            //返回資訊為空
            if (xmlHttp.responseText.trim() == "") {
            //如果已存在id為contents的div 則移除然後重新生成
                if ($("contents"))
              document.body.removeChild(divtable);
            }
            else {
                createTable(xmlHttp.responseText);
                
            }
        } else {
            window.alert("未知錯誤!");
            return false;
        }
    }
}

建立裝在返回結果的載體DIV

function createTable(strtable, divheight,obj,e) {
    if ($("contents"))
        document.body.removeChild(divtable);
    divtable = window.document.createElement("div");
    divtable.setAttribute("id", "contents");
     divtable.setAttribute("class", "tbData");
    divtable.style.position = "absolute";
    divtable.innerHTML = "";
    var strcon = "<iframe style=\"position: absolute;z-index: 2;height:0px;width:0px;\" frameborder=\"0\"></iframe>";
    divtable.innerHTML = strcon + strtable;
    divtable.zIndex = "100";
    divtable.style.zIndex = "800";
    divtable.style.overflow = "auto";
    divtable.style.height = "235px";
    divtable.style.width = "430px";
   var opt = $(txtname).offsetParent;
   var oft = $(txtname).offsetTop;
   var ofh = $(txtname).offsetHeight;
   var ofl = $(txtname).offsetLeft;
 
 	divtable.style.top = oft + ofh + "px";
    divtable.style.left = ofl + "px";

    document.body.appendChild(divtable);
}

遮蔽幾個特殊鍵盤按鍵

document.onkeydown = function (e) {
    if (document.getElementById("gvice")) {
        e = window.event || e;
        switch (e.keyCode) {
            case 38:
                // 上方向鍵
                currentLine--;
                changeItem();
                break;
            case 40:
                // 下方向鍵
                currentLine++;
                changeItem();
                break;
                // Backspace
            case 32:
                MoveDivTable();
                break;
                // Tab
            case 9:
                MoveDivTable();
                // Enter
            case 13:
                MoveDivTable();
                break;
            default:
                break;
        }
    }
}

選中後為文字框賦值

// 選擇行
function changeItem() {
    var it = document.getElementById("gvice");
    for (var j = 0; j < it.rows.length; j++) {
        it.rows[j].className = "bsltrowc";
    }
    if (currentLine < 0) {
        currentLine = it.rows.length - 1;
    }
    if (currentLine == it.rows.length) {
        currentLine = 0;
    }
    if (it.rows.length == 1) {
        currentLine = 0;
    }

    if (it.rows[currentLine]) {
        it.rows[currentLine].className = "sltrowc";
        $(txtnameid).value = it.rows[currentLine].id;
        $(txtname).value = it.rows[currentLine].cells[1].innerHTML.split('-')[0];
    }
}
//單擊取值
function clickItem(clicktLine) {
    if (document.all) {
        var it = document.getElementById("gvice").children[0];
    }
    else {
        var it = document.getElementById("gvice");
    }
    for (i = 0; i < it.rows.length; i++) {
        it.rows[i].className = "bsltrowc";
    }
    //為text文字框賦值
    it.rows[clicktLine].className = "sltrowc";
    $(txtnameid).value = it.rows[clicktLine].id;
    $(txtname).value = it.rows[clicktLine].cells[1].innerHTML;//.split('-')[0];
    currentLine = clicktLine;

    if (btntgetinfo != null && btntgetinfo != "")
        $(btntgetinfo).click();
}
//單擊取值
function clickItemGoods(clicktLine) {
    if (document.all) {
        var it = document.getElementById("gvice").children[0];
    }
    else {
        var it = document.getElementById("gvice");
    }
    for (i = 0; i < it.rows.length; i++) {
        it.rows[i].className = "bsltrowc";
    }
//為text文字框賦值
    it.rows[clicktLine].className = "sltrowc";
    $(txtnameid).value = it.rows[clicktLine].id;
    $(txtname).value = it.rows[clicktLine].cells[1].innerHTML;//.split('-')[0];
    $(txtclassname).value = it.rows[clicktLine].cells[2].innerHTML;//.split('-')[0];
    $(txtbrandname).value = it.rows[clicktLine].cells[3].innerHTML;//.split('-')[0];
    if ($(txtclassname).value.length < 1)
    {
        $(txtclassname).value = "";
    }
    if ($(txtbrandname).value.length < 1)
    {
        $(txtbrandname).value = "";
    }
    currentLine = clicktLine;

    if (btntgetinfo != null && btntgetinfo != "")
        $(btntgetinfo).click();
}

//移除Div
function MoveDivTable() {
    if ($("contents")){
        document.body.removeChild(divtable);
       }
	if ($("contentsRow")){
	document.getElementById("UpdatePanel2").removeChild(divtable);
	}
    if (btntgetinfo != null && btntgetinfo != "")
        $(btntgetinfo).click();
}
//焦點消失後移除div
function MoveDivTableBlur() {
setTimeout(function () {
    if ($("contents")){
        document.body.removeChild(divtable);
       }
    if ($("contentsRow")){
        document.getElementById("UpdatePanel2").removeChild(divtable); 
       }
}, 200)
}

總結:在獲取生成div位置時遇到一些問題 就是關於 offsetTop 以及 offsetLeft 的如何取距離父層的長度,詳情可見我的另一篇部落格。