欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Javascript實(shí)現(xiàn)獲取及設(shè)置光標(biāo)位置的方法

 更新時(shí)間:2015年07月21日 12:19:01   作者:華宰  
這篇文章主要介紹了Javascript實(shí)現(xiàn)獲取及設(shè)置光標(biāo)位置的方法,涉及javascript針對(duì)頁面光標(biāo)位置的相關(guān)操作技巧,具有良好的兼容性,非常簡(jiǎn)單實(shí)用,需要的朋友可以參考下

本文實(shí)例講述了Javascript實(shí)現(xiàn)獲取及設(shè)置光標(biāo)位置的方法。分享給大家供大家參考。具體如下:

在項(xiàng)目開發(fā)中經(jīng)常遇到input等設(shè)置光標(biāo)位置到最后的問題,今天我查了一下Google,找到了在IE、Firefox、Opera等主流瀏覽器的獲取光標(biāo)位置(getCursortPosition)以及設(shè)置光標(biāo)位置(setCursorPosition)的函數(shù)。

1. 獲取光標(biāo)位置函數(shù):

function getCursortPosition (ctrl) {
  var CaretPos = 0;  // IE Support
  if (document.selection) {
  ctrl.focus ();
    var Sel = document.selection.createRange ();
    Sel.moveStart ('character', -ctrl.value.length);
    CaretPos = Sel.text.length;
  }
  // Firefox support
  else if (ctrl.selectionStart || ctrl.selectionStart == '0')
    CaretPos = ctrl.selectionStart;
  return (CaretPos);
}

2. 設(shè)置光標(biāo)位置函數(shù):

function setCaretPosition(ctrl, pos){
  if(ctrl.setSelectionRange)
  {
    ctrl.focus();
    ctrl.setSelectionRange(pos,pos);
  }
  else if (ctrl.createTextRange) {
    var range = ctrl.createTextRange();
    range.collapse(true);
    range.moveEnd('character', pos);
    range.moveStart('character', pos);
    range.select();
  }
}

希望本文所述對(duì)大家的javascript程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論