完整代码附上:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Virtual Numeric Keyboard</title>
<style>
.keyboard {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
height: 50vh;
background-color: #f9f9f9;
border-top: 1px solid #ccc;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 0px;
padding: 0px;
}
button {
padding: 0px;
font-size: 26px;
border: 1px solid #ccc;
background-color: transparent;
}
.keyboard button:active {
background-color: lightblue;
}
</style>
</head>
<body>
<input type="text" id="input">
<div class="keyboard" id="keyboard" style="display: none;">
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>7</button>
<button>8</button>
<button>9</button>
<button>清空</button>
<button>0</button>
<button>确定</button>
</div>
<script>
const input = document.getElementById('input');
const keyboard = document.getElementById('keyboard');
var setTime = null
input.addEventListener('focus', () => {
keyboard.style.display = 'grid';
});
input.addEventListener('blur', function (evenet) {
setTime = setTimeout(() => {
keyboard.style.display = 'none';
}, 10)
});
keyboard.addEventListener('click', (event) => {
if (event.target.tagName === 'BUTTON') {
clearTimeout(setTime);
const value = event.target.textContent;
if (value === '清空') {
input.value = '';
} else if (value === '确定') {
// 处理确认操作
console.log('确认输入:', input.value);
keyboard.style.display = 'none';
} else {
input.value += value;
let length = input.value.length
input.focus();
input.setSelectionRange(length, length);
}
}
});
</script>
</body>
</html>
效果图: