原生js制作简单的数字键盘_javascript技巧

js教程评论4.3K views阅读模式

一、起因

  最近支付的同事说,数字键盘有些问题;在移动设备上有时候比较难出现点(.) 和数字在一起的格局;因此,考虑到这种情况,就建议手写个模拟键盘了。花了一晚上的时间,写了个简单的键盘,基本能用。考虑到有的开发者没有使用juqery,就使用原生的js了。

  Github地址:https://github.com/vczero/keyboard

二、截图如下

三、体验地址(需要点击input才能弹出数字键盘的哦)

URL: http://vczero.github.io/num_key/index.html

四、代码比较简单,直接贴了

;(function(exports){
  var KeyBoard = function(input, options){
    var body = document.getElementsByTagName('body')[0];
    var DIV_ID = options && options.divId || '__w_l_h_v_c_z_e_r_o_divid';
    
    if(document.getElementById(DIV_ID)){
      body.removeChild(document.getElementById(DIV_ID));
    }
    
    this.input = input;
    this.el = document.createElement('div');
    
    var self = this;
    var zIndex = options && options.zIndex || 1000;
    var width = options && options.width || '100%';
    var height = options && options.height || '193px';
    var fontSize = options && options.fontSize || '15px';
    var backgroundColor = options && options.backgroundColor || '#fff';
    var TABLE_ID = options && options.table_id || 'table_0909099';
    var mobile = typeof orientation !== 'undefined';
    
    this.el.id = DIV_ID;
    this.el.style.position = 'absolute';
    this.el.style.left = 0;
    this.el.style.right = 0;
    this.el.style.bottom = 0;
    this.el.style.zIndex = zIndex;
    this.el.style.width = width;
    this.el.style.height = height;
    this.el.style.backgroundColor = backgroundColor;
    
    //样式
    var cssStr = '';
    
    //Button
    var btnStr = '
  
完成
'; //table var tableStr = ' '; tableStr += ' '; tableStr += ' '; tableStr += ' '; tableStr += ' '; tableStr += ' '; tableStr += '
1 2 3
4 5 6
7 8 9
. 0删除
'; this.el.innerHTML = cssStr + btnStr + tableStr; function addEvent(e){ var ev = e || window.event; var clickEl = ev.element || ev.target; var value = clickEl.textContent || clickEl.innerText; if(clickEl.tagName.toLocaleLowerCase() === 'td' && value !== "删除"){ if(self.input){ self.input.value += value; } }else if(clickEl.tagName.toLocaleLowerCase() === 'div' && value === "完成"){ body.removeChild(self.el); }else if(clickEl.tagName.toLocaleLowerCase() === 'td' && value === "删除"){ var num = self.input.value; if(num){ var newNum = num.substr(0, num.length - 1); self.input.value = newNum; } } } if(mobile){ this.el.ontouchstart = addEvent; }else{ this.el.onclick = addEvent; } body.appendChild(this.el); } exports.KeyBoard = KeyBoard; })(window);

五、简单demo

 
 
   
     
  
     模拟数字键盘
     
  
   
   
     
  


以上所述就是本文的全部内容了,希望大家能够喜欢。

企鹅博客
  • 本文由 发表于 2020年8月31日 20:43:27
  • 转载请务必保留本文链接:https://www.qieseo.com/414002.html

发表评论