首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >accounting.js将光标保持在十进制值的末尾。

accounting.js将光标保持在十进制值的末尾。
EN

Stack Overflow用户
提问于 2016-06-15 13:26:30
回答 2查看 1.2K关注 0票数 1

我正在使用accoungting.js插件格式化货币。唯一的问题是,只要输入任何内容,它就会将光标放在值的末尾,而且由于我为currency保持了2小数值的精度,所以它阻止了我输入更多。我没有找到任何源代码,这是用于编辑值,一旦你键入。我怎么才能把这事做好?找到解决办法或黑客了吗?

代码语言:javascript
复制
<input autocomplete="off" type="text" id="Price"/>

JS

代码语言:javascript
复制
var options = {
    symbol : "£",
    decimal : ".",
    thousand: ",",
    precision : 2,
    format: "%s%v"
};

$("#Price")
  .on("input",
    function() {
      var _this = $(this);
      debugger;
      var val = _this.val().startsWith("£") ? _this.val().split("£")[1] : _this.val();
      var value=accounting.formatMoney(val,options);
      _this.val(value);
});

演示

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-06-15 13:41:36

完全RE编辑的

(为清晰起见)

我认为,这是accounting.js的一种bug修复。

问题是在输入字段中在keyup (或像这里这样的input事件)上使用游标的位置。

在这个解决方案中,我切换回了keyup事件,因为-奇怪的是- input事件没有提供keycode编号。

这里是最后的解决方案

再加上我的这个小剧本(部分是从一年前的答案和一些作品中得到的.不记得消息来源)

代码语言:javascript
复制
// ---------------------------------------------------------------------------  What is the browser ?

var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
    // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined';   // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
    // At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !!window.chrome && !isOpera;              // Chrome 1+
var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6

function GetCursorPos (field) {
    // Initialize
    iCaretPos = 0;

    if (isIE){  //(document.selection) {

        // Set focus on the element
        field.focus();

        // To get cursor position, get empty selection range
        oSel = field.createTextRange();

        // Move selection start to 0 position
        oSel.moveStart('character', -field.value.length);

        // The caret position is selection length
        iCaretPos = oSel.text.length;
    }
    if (isChrome||isSafari){    //(field.selectionStart || field.selectionStart == '0')
        iCaretPos = field.selectionStart;
    }
    if (isFirefox){
        iCaretPos = field.selectionStart;
    }

    return iCaretPos;
}

function SetCursorPos (field,Pos) {
    // Set focus on the element
    field.focus();

    if (isIE){
        field.selectionStart=Pos;
    }
    if (isChrome||isSafari){
        field.setSelectionRange(Pos,Pos);
    }
    if (isFirefox){
        field.selectionStart=Pos;
    }
    return;
}

然后,对于accounting.js,管理onkeyup值更新的方法是:

代码语言:javascript
复制
$("#Price")
.on('keyup', function (event) {
    var val = this.value;
    var x = event.keyCode;                  // Get the keycode for backspace check
    var offset=0;                           // Set the offset to zero by default.

    if(((x>=96)&&(x<=105))||((x>=37)&&(x<=40))||(x==8)||(x==46)){   // Allow digits from 0 to 9 AND arrows AND backspace AND Delete

        var dotPos = val.indexOf(".");          // Check for dot position.
        var offsetComa = val.length%4;          // Variable used to check if a coma is to be added.

        // Offset conditions
        if(val.length==1){
            offset=1;                           // When the first digit is entered in the field, it's time to offset by 1 for the "£" to be added.
        }
        if(val.length>1){
            if(offsetComa==0){                  // when there is no remainder of val.length/4, it's time to offset 1 for the coma to be added.
                offset=1;
            }
            if((offsetComa==0)&&((x==46)||(x==8))){ // when there is no remainder of val.length/4, BUT WE REMOVED A CHARACTER.  offset -1 for the coma to be added.
                offset=-1;
            }
            if(dotPos==1){                      // If dot is right after "£" => user has backspaced!
                val="";                         // Consider val as empty!
            }
            if(dotPos==-1){                     // If no dot present reinsert it!
                val = val.slice(0, cursorPos-1) + "." + val.slice(cursorPos);
            }
            if(cursorPos==val.length-2){        // If inputting the second decimal, remove the possible third to avoid rounding.
                val = val.slice(0, cursorPos+1);
            }
            if(cursorPos==val.length-3){        // If inputting decimals, clear offset.
                offset=0;
                val = val.slice(0, val.length-1)
            }
        }

    }else{                                      // Removes any non-digit character
        if(x!=8){
            cursorPos = GetCursorPos(this);
            val = val.slice(0, cursorPos-1) + val.slice(cursorPos);


            if(val.charAt(cursorPos-1)=="."){   // decimal point
                cursorPos+=1;
            }

            this.value = val;
            SetCursorPos(this,cursorPos-1);
        }
    }

    var hasCurrencySymbol = val.startsWith('£');
    var formatted = accounting.formatMoney(val.substr(hasCurrencySymbol ? 1 : 0), options);
    if(formatted=="£0.00"){
        formatted=""                        // Empty the field instead of showing the problematic "£0.00"
    }

    cursorPos = GetCursorPos(this);         // Get previous cursor position
    this.value = formatted;                        // Return the value to field
    SetCursorPos(this,cursorPos+offset);    // Correct cursor position
});

它在onkeyup上管理计算的光标偏移量。

它还管理后台/删除反向偏移量。

小数可以输入。

奖励,它立即删除所有非数字字符。

:D

看一看 最后一次在这里

票数 1
EN

Stack Overflow用户

发布于 2016-06-15 14:34:48

当以编程方式更改输入值时,还需要恢复游标位置,因为浏览器会丢失该信息。

最简单的方法是恢复更改前使用的位置。

代码语言:javascript
复制
// pseudocode
.on('input', function () {
    var cursorPosition = this.selectionEnd;

    var val = this.value;
    var hasCurrencySymbol = val.startsWith('£');
    var formatted = accounting.formatMoney(val.substr(hasCurrencySymbol ? 1 : 0), options);

    this.value = formatted;
    this.setSelectionRange(cursorPosition, cursorPosition);
});

但可能更需要的是将光标放在刚刚插入的数字后面。下面的代码通过新输入文本和旧输入文本之间的长度差异来移动最后记住的光标位置,这不是理想的解决方案(特别是第一次插入的数字),但是是进一步改进的良好起点。

代码语言:javascript
复制
.on('input', function () {
    var cursorPosition = this.selectionEnd;

    var val = this.value;
    var hasCurrencySymbol = val.startsWith('£');
    var formatted = accounting.formatMoney(val.substr(hasCurrencySymbol ? 1 : 0), options);
    var lengthDiff = formatted.length - val.length;

    this.value = formatted;
    this.setSelectionRange(cursorPosition + diff, cursorPosition + diff);
});

代码使用setSelectionRange,所有流行的浏览器(包括IE9+)都支持它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37836838

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档