就像按“ a”键并输入“ b”一样。似乎有很多与此类似的旧问题,但是答案似乎没有用。不知道这是由于KeyboardEvent.initKeyEvent()
被弃用还是我的代码存在缺陷,但我做错了。
以下是我尝试过的一些示例:
document.addEventListener("keydown", evt => {
evt.target.dispatchEvent(new KeyboardEvent('keydown', {"keyCode": 9, "which": 9}))
})
答案 0 :(得分:1)
新答案:
const data = [
"apple",
"banana",
"pear",
"orange",
"lemon",
"lime",
"grape",
"cherry",
"peach",
"plum",
"grapefruit",
"watermelon",
"kiwi"
]
let suggestions = [];
const container = document.getElementById("data");
let index = 0;
function handleChange(e) {
const value = e.target.value;
container.innerHTML = "";
index = 0 ;
suggestions = value ? data.filter(ele => ele.toLowerCase().includes(value)) : [];
suggestions.forEach(ele => {
const suggestion = document.createElement("div");
suggestion.textContent = ele;
container.append(suggestion);
})
}
function handleKeydown(e) {
if (e.keyCode === 9 && suggestions.length) {
e.preventDefault();
e.target.value = suggestions[index];
index === suggestions.length - 1 ? index = 0 : index += 1;
} else if (e.keyCode === 13) {
container.innerHTML = ""
index = 0;
suggestions = [];
}
}
<div> Type A Fruit </div>
<input type="text" onkeydown="handleKeydown(event)" oninput="handleChange(event)" />
<div id="data"> </div>
旧答案:
似乎没有人为打开选择下拉菜单的方法;这是我能想到的最好的实现。
let selected = false;
function handleSelect(e) {
if (e.keyCode === 9 && !selected) {
e.preventDefault()
const options = Array.from(e.target.children);
if (!e.target.classList.contains('open')) {
e.target.setAttribute('size', e.target.options.length)
e.target.classList.toggle('open')
} else {
const index = options.findIndex(option => !!option.selected)
if (options[index + 1]) {
options[index + 1].selected = true;
} else {
options[0].selected = true;
}
}
}
if (e.keyCode === 13) {
e.preventDefault();
if (e.target.classList.contains('open')) {
e.target.classList.toggle('open')
e.target.setAttribute('size', "initial")
selected = true;
}
}
if (e.keyCode === 38 || e.keyCode === 40) {
if (!e.target.classList.contains('open')) e.preventDefault();
}
}
function handleBlur() {
selected = false;
}
function handleClick(e) {
Array.from(e.target.children)[1].focus();
}
.container {
display: flex;
}
label {
width: 100px;
pointer-events: none;
}
select {
pointer-events: none;
}
.open {
position: absolute;
left: 110px;
}
<div> click and hit tab </div>
<div class="container" onclick="handleClick(event)">
<label for="cars">Choose a car:</label>
<select onkeydown="handleSelect(event)" onclick="handleClick(event)" onblur="handleBlur()" name="cars" id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</div>