亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用更嚴格的限制自定義 `<input>` 元素

如何使用更嚴格的限制自定義 `<input>` 元素

繁花不似錦 2021-09-30 09:30:24
我有一個 html<input>元素,我只想接受數字并在移動設備上將其識別為數字字段。我還希望吞下無效字符,就像標準type=number吞咽不允許的字符一樣。我已經嘗試過顯而易見的,type=number但它有許多缺點。具體來說,它允許 'e'、'+' 和 '-'(至少在 chrome 中),但這些很容易用一些 JS 修復。真正的問題在于'.' 字符,我希望能夠輸入浮點數,例如“0.10”、“5.5054”,但不想輸入無效的字符串,例如“0.10.1”。我試圖通過只允許 1 '.' 來解決這個問題。一次,但這失敗了input.value,因為瀏覽器對它進行了按摩,例如“5”。變為 '5','5..' 變為空(?。?,并且似乎不可能獲得輸入中鍵入的原始字符串值。以上意味著檢查現有的 '.' 并采取行動似乎是死胡同......核心問題:有沒有辦法檢查和符合輸入?'有沒有一種方法可以將輸入標記為一個沒有后勤包袱的數字type=number?注意:* 我意識到你可以粘貼任何你想要的東西,我認為這種行為是病態的,不應該被輸入預防所覆蓋。更新澄清一下,我已經嘗試過keypress, keydownetc 事件,但它們還不夠,因為我想查看當前輸入中存在多少個 '. 以選擇是否允許另一個。此時input.value已經被瀏覽器按摩以刪除'.'。我想根據當前輸入的 '.' 的數量有條件地允許字符。例子HTML(為簡潔起見,角度樣式綁定)<input type="number" (keydown)="keyDown()">JSfunction keyDown($event: KeyboardEvent) {  const inputField = // obtain reference to input element  const value = inputField.value;  if ( value.indexOf('.') !== -1 && $event.key === '.') { // disallow another . if one is present    // ! input field prunes . so this check isn't sufficient    $event.preventDefault();    return;  }  // This is the crux of the problem e.g.  // type 5. into input field, value === 5  // type 5.. into the input field, value === null  // Since the . char is removed by the input element there's no way to know how many are present!  console.log(value);}概括有沒有辦法在<input>不使用type=number屬性設置的情況下發出信號類型為 number 的信號。即移動設備識別和顯示數字鍵盤等對于一個<input>有type=number沒有辦法吞下所有不會導致有效數字的鍵輸入在瀏覽器將字符添加到輸入中之前,不會進行 janky 刪除 keyup
查看完整描述

3 回答

?
叮當貓咪

TA貢獻1776條經驗 獲得超12個贊

一種稍微不同的方法。它允許數字、只有 1 個句點和退格。所有其余的KeyboardEvent.keys 包括ctrl + v和ctrl + c 都被忽略。但是,如果希望允許它們,您可以這樣做。


為了檢查字符是否是10數字之一,我使用的是event.key因為它們可以有兩個不同的代碼:Digits[0-9]和Numpad[0-9]。但是對于句號和退格,我使用的是event.code因為它們只有一個代碼。


const input = document.querySelector("#number_input");


const App = {

  isDigit: function(key) {

    const digits = [

      "0",

      "1",

      "2",

      "3",

      "4",

      "5",

      "6",

      "7",

      "8",

      "9"

    ];

    return digits.includes(key);

  },

  isPeriod: function(code) {

    return code === "Period";

  },

  isBackSpace: function(code) {

    return code === "Backspace";

  },

  handleEvent: function(event) {

    const key = event.key;

    const code = event.code;

    const value = input.value;

    if (App.isDigit(key) || App.isPeriod(code) || App.isBackSpace(code)) {

      if (App.isPeriod(code) && value.indexOf(key) !== -1) {

        event.preventDefault();

      }

    } else {

      event.preventDefault();

    }

  }

};


input.onkeydown = App.handleEvent

<input id="number_input" />

一個聰明的黑客

由于您堅持使用數字輸入。第一次使用,一個虛擬文本輸入,您可以使用 CSS 或 Js 隱藏它并驗證其值而不是數字輸入。


const input = document.querySelector("#number_input");

const dummyInput = document.querySelector("#dummy_input")

const App = {

  isDigit: function(key) {

    const digits = [

      "0",

      "1",

      "2",

      "3",

      "4",

      "5",

      "6",

      "7",

      "8",

      "9"

    ];

    return digits.includes(key);

  },

  isPeriod: function(code) {

    return code === "Period";

  },

  isBackSpace: function(code) {

    return code === "Backspace";

  },

  handleEvent: function(event) {

    const key = event.key;

    const code = event.code;

    const dummyValue = dummyInput.value;

    if (App.isBackSpace(code)) {

      dummyInput.value = dummyValue.substring(0, dummyValue.length - 1)

    } else {

      if (App.isDigit(key) || App.isPeriod(code)) {

        if (App.isPeriod(code) && dummyValue.indexOf(key) !== -1) {

          event.preventDefault();

        } else {

          dummyInput.value += event.key

        }

      } else {

        event.preventDefault();

      }

    }

  }

};


input.onkeydown = App.handleEvent

<input type="number" id="number_input" />

<input type="text" id="dummy_input" />

更新

所有使用 input[type="number"] 的答案都有問題。您可以通過鼠標滾輪/微調器將輸入值更改為負數。要解決此問題,請為輸入設置最小值。


<input type="number" min="1" id="number_input" />

您需要監聽onchange事件,然后更改虛擬輸入的值。


const input = document.querySelector("#number_input");

const dummyInput = document.querySelector("#dummy_input")

const App = {

  isDigit: function(key) {

    const digits = [

      "0",

      "1",

      "2",

      "3",

      "4",

      "5",

      "6",

      "7",

      "8",

      "9"

    ];

    return digits.includes(key);

  },

  isPeriod: function(code) {

    return code === "Period";

  },

  isBackSpace: function(code) {

    return code === "Backspace";

  },

  handleEvent: function(event) {

    const key = event.key;

    const code = event.code;

    const dummyValue = dummyInput.value;

    if (App.isBackSpace(code)) {

      dummyInput.value = dummyValue.substring(0, dummyValue.length - 1)

    } else {

      if (App.isDigit(key) || App.isPeriod(code)) {

        if (App.isPeriod(code) && dummyValue.indexOf(key) !== -1) {

          event.preventDefault();

        } else {

          dummyInput.value += event.key

        }

      } else {

        event.preventDefault();

      }

    }

  },

  handleChange: function(event) {

    dummyInput.value = event.target.value

  }

};


input.onkeydown = App.handleEvent;

input.onchange = App.handleChange;

<input type="number" min="1" id="number_input" />

<input type="text" id="dummy_input" />


查看完整回答
反對 回復 2021-09-30
?
慕斯王

TA貢獻1864條經驗 獲得超2個贊

更新


答案根據需求變化進行更新。


好的,我嘗試解決另一個問題,即


根據以下代碼粘貼您不能粘貼任何內容,您只能粘貼數字,如果您嘗試粘貼字符串,輸入框將自動變為空:)


  let special = document.getElementById('inputField');

  special.addEventListener("keypress", function(e) {

  let dot = 46;

  // allowed char: 0-9, .

  let allow_char = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, dot];

  if (allow_char.indexOf(e.which) !== -1) {

    // only 1 dot

    if (e.which == 46 && special.value.indexOf('.') !== -1)

      e.preventDefault();

  } else {

    e.preventDefault();

  }

});


function checkString()

{

  setTimeout(() => {

  var value = document.getElementById("inputField").value;

  value = parseInt(value);

    if(isNaN(value))

      document.getElementById("inputField").value = "";

    }, 100);


}

  <input type="number" id="inputField" onpaste="checkString()"/>


查看完整回答
反對 回復 2021-09-30
  • 3 回答
  • 0 關注
  • 205 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號