簡體   English   中英

有沒有辦法像使用 type=“search” 一樣清除輸入 type=“number”

[英]Is there a way to clear an input type=“number” like when using type=“search”

我有一個Bootstrap 4 form ,其中包含一些數字、一些文本和其他 email 的各種inputs

我已經通過添加以下內容對我的文本inputs進行了排序,在input中顯示“x”

input[type="search"]::-webkit-search-cancel-button {
    -webkit-appearance: searchfield-cancel-button;
}

但我希望我的“號碼”和“電子郵件” input相同

我嘗試使用以下內容查看它是否有效,但它沒有

input[type="search"]::-webkit-search-cancel-button {
    -webkit-appearance: searchfield-cancel-button;
}

我還使用了下面的CSS在使用type='number'時刪除了箭頭,並且再次正常工作

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

在我恢復使用regex作為我的數字inputs之前,我想我會問

在此處輸入圖像描述

HTML

<input id="one" class="form-control" type="search" value="Test company name" />
<input id="two" class="form-control" type="number" value="123456" />
<input id="two" class="form-control" type="number" value="12345634" />

如您所見,我的數字input沒有顯示箭頭,這正是我想要的。

有好消息也有壞消息。 首先是壞消息:webkit 取消按鈕僅可用於search類型的輸入字段。

好消息:您可以自己創建按鈕。

復制並粘貼以下 CSS:

.close-button {
  color: #1e52e3;
  font-size: 12pt;
  font-family: monospace,sans-serif;
  font-weight: 600;
  position: absolute;
  z-index: 2;
  display: none;
}

.close-button:hover {
  cursor: pointer;
}

並通過反復試驗將字體大小更改為合適的大小。

然后在相關 HTML 中的</body>標記之前添加此 Javascript:

<script>
var fields = document.querySelectorAll('input[type=number],input[type=email]');

fields.forEach(function(input) {
  let x = document.createElement('span');
  x.classList.add('close-button');
  x.innerHTML = 'x';
  x.style.left = input.clientWidth - 15;
  x.onmousedown = removeContent;
  input.parentNode.insertBefore(x, input);
  input.oninput = toggleCloseButton;
  input.addEventListener( 'focusin', toggleCloseButton);
  input.addEventListener( 'focusout', hideCloseButton);
});

function toggleCloseButton() {
   if (this.value.length > 0) {
     this.previousSibling.style.display = 'block';
   } else {
     this.previousSibling.style.display = 'none';
   }
}

function hideCloseButton() {
  this.previousSibling.style.display = 'none';
}

function removeContent(){
  this.nextSibling.value = '';
  this.nextSibling.focus();
}
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM