如何通過js實現頁面光標位置的控制


需求:對於通知書打印之后條形碼批量掃描錄入的功能,需要在上一個text取值改變后將光標的位置移動到下一個為空的text中,當遍歷到最后一個text之后,光標移動到保存按鈕的位置上。
實現:
1.因為對於不同的瀏覽器(這里指的是個人非常討厭的ie,就他特別),處理方法不同,所以需要事先判斷用戶使用的瀏覽器類型
eg:function getOs() 
   var OsObject = ""; 
   if(navigator.userAgent.indexOf("MSIE")>0) { 
        return "MSIE"; 
   } 
   if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){ 
        return "Firefox"; 
   } 
   if(isSafari=navigator.userAgent.indexOf("Safari")>0) { 
        return "Safari"; 
   }  
   if(isCamino=navigator.userAgent.indexOf("Camino")>0){ 
        return "Camino"; 
   } 
   if(isMozilla=navigator.userAgent.indexOf("Gecko/")>0){ 
        return "Gecko"; 
   } 
調用該方法就可以返回瀏覽器的類型了,之后就可以針對瀏覽器采取措施。需要做的操作有:光標移動的事件觸發,以及光標移動的位置。
在系統中我的實現是:
var bowserType = getOs();
if(bowserType=="MSIE"){
$("#advicenote_recordcode_recordBatch_form :text").bind("propertychange",function(){
var trId = $(this).parent().parent().attr("id");//獲取當前文本框最外層tr的id
setFocus(trId);
});
}else{
$("#advicenote_recordcode_recordBatch_form :text").on("input",function(){
var trId = $(this).parent().parent().attr("id");//獲取當前文本框最外層tr的id
setFocus(trId);
});
}
遍歷表單中的text,ie瀏覽器通過propertychange方法觸發光標異動事件,其他瀏覽器使用on input方法觸發事件,之后因實際情況而自行決定獲得需要光標移動到的位置。
之后就需要設置光標的位置了,使用的是js的focus方法,很簡單,不多說了。
function setFocus(nowTrId){
nowTrId = parseInt(nowTrId)+1;//計算獲得下一個tr的id
var textValue = $("#"+nowTrId+" :text").val();
//光標焦點異動
if(textValue==""){
$("#"+nowTrId+" :text").focus();
}else{
var lastMark = $("#"+nowTrId+" input[name='lastTdMark']").val();
if(lastMark=="0"){
setFocus(nowTrId);
}else if(lastMark == "1"){
$("#advicenote_recordcode_recordBatch_form input[name='saveBtn']").focus();
}
}
}
擴展:幾種常用到的值改變觸發事件

             focus:獲得焦點時觸發事件

             keyup:按鍵彈起時觸發事件

             keypress:按鍵按下時觸發事件(先響應事件,再顯示輸入結果(獲得的是上一次結果),可能被輸入法攔截)

             propertychange:屬性改變時觸發事件(不管是獲得焦點還是value改變等)

優缺點分析:keyup:當鍵盤按下又松開的時候會出發事件,但是當按到例如ctrl等特殊用途或無用的按鍵時,也會觸發時間

                     propertychange:只針對ie8有效,

 

<!--

$(".txt").change(function(){

    $(".txt").val("");

});

$(".txt").focus(function(){

    $(".txt").val("");

});

$(".txt").keyup(function(){

    var txtChange = $("input").val();

    $("#p2").html(txtChange);

});

$(".txt").keypress(function(){

    var txtChange = $("input").val();

    $("#p2").html(txtChange);

});

$(".txt").bind("propertychange",function(){

    var txtChange = $("input").val();

    $("#p2").html(txtChange);

});

    -->


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM