首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

JS 實現輸入框一鍵清空叉號:原生與 Vue/React 組件寫法

     編輯:程式設計疑難解答

原生 JS 實現

<input type="text" id="search" placeholder="搜索...">
<span id="clear" style="display:none; cursor:pointer;">×</span>

<script>
const input = document.getElementById('search');
const clear = document.getElementById('clear');
input.addEventListener('input', () => {
    clear.style.display = input.value ? 'inline' : 'none';
});
clear.addEventListener('click', () => {
    input.value = '';
    clear.style.display = 'none';
    input.focus();
});
</script>

Vue 3 組件

<script setup>
import { ref } from 'vue';
const model = ref('');
const showClear = computed(() => model.value.length > 0);
const clear = () => { model.value = ''; };
</script>

<template>
  <div class="input-wrapper">
    <input v-model="model" @focus="() => {}" />
    <span v-if="showClear" @click="clear" class="clear-icon">×</span>
  </div>
</template>

React Hooks 組件

function SearchInput() {
  const [value, setValue] = useState('');
  return (
    <div style={{position: 'relative'}}>
      <input value={value} onChange={e => setValue(e.target.value)} />
      {value && <span onClick={() => setValue('')} style={{position:'absolute',right:8,top:'50%',transform:'translateY(-50%)',cursor:'pointer'}}>×</span>}
    </div>
  );
}

無障礙建議

  • 添加 aria-label="清空輸入"。
  • 鍵盤可聚焦 tabindex="0",Enter/Space 觸發清空。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved