当我的重点和选择从向上和向下箭头键,它是不工作,请你能帮我这个。
下面是我的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<div style="margin-left: 500px; margin-top: 200px;">
<form action="" method="post">
<select id='country' name="country" style='width: 200px;'>
<optgroup label='div1'>
<option value='1'>India</option>
<option value='2'>America</option>
</optgroup>
<optgroup label='div2'>
<option value='3'>Pakistan </option>
<option value='4'>Afghanistan</option>
</optgroup>
</select>
<br/>
<input type="submit" name="save" value="submit">
</form>
</div>
<script>
$(document).ready(function(){
$("#country").select2();
$("#country").on("select2:open", function (e) {
// Highlight the initially selected option
highlightSelected();
});
$("#country").on("select2:select", function (e) {
// Highlight the selected option when selected via mouse
highlightSelected();
});
// Listen for keydown events
$("#country").on("keydown", function (e) {
var currentOption = $(this).find(":selected");
var highlightedOption;
if (e.which === 38) { // Up arrow
highlightedOption = currentOption.prev();
} else if (e.which === 40) { // Down arrow
highlightedOption = currentOption.next();
}
if (highlightedOption.length > 0) {
$(this).find("option").removeClass("highlight");
highlightedOption.addClass("highlight");
}
});
function highlightSelected() {
var selectedOption = $("#country").find(":selected");
$("#country").find("option").removeClass("highlight");
selectedOption.addClass("highlight");
}
});
</script>
</body>
</html>
字符串
我希望当我从focus中聚焦元素时,它应该能为键盘上的上下箭头工作。
...........................................................................................................................................
1条答案
按热度按时间zd287kbt1#
字符串