如何使用jQuery来触发选择框的点击悬停
在这篇文章中,我们要学习的是,如何在鼠标悬停时触发选择框或下拉菜单的点击事件,使用jQuery。
为了给选择框创建这样的行为,我们将使用jQuery的attr()方法。这个方法是用来设置或返回网页上所选元素的属性和值。注意,我们将不能直接触发悬停时的点击事件,所以我们使用attr()方法来完成工作。
方法:我们将在选择框的以下id或类上调用hover()方法。我们将使用attr()方法来获得选择框的大小,在同一个方法中,我们将改变它的大小为1,所以当我们将光标从选择框中移出时,它将恢复到默认的大小。通过使用这种方法,我们将能够在鼠标悬停时显示整个列表,而当用户从列表中选择任何一个值时,它又回到了默认视图。
示例:
<!DOCTYPE html>
<head>
<script src=
"https://code.jquery.com/jquery-3.6.0.min.js"
integrity=
"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin=
"anonymous">
</script>
<title>Trigger click on hover on the select box</title>
<style>
body {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
.main{
display: flex;
align-items: center;
align-items: center;
justify-content: center;
margin: 50px;
}
.main div{
width: 100px;
height: 100px;
background-color: red;
margin: 10px;
border-radius: 50%;
cursor: pointer;
}
#select_value{
outline: none;
width: 120px;
}
</style>
</head>
<body>
<div class="main">
<select id="select_value">
<!-- There are five items on the list -->
<option value="">Select</option>
<option value="Actor">Actor</option>
<option value="Dancer">Dancer</option>
<option value="Singer">Singer</option>
<option value="Musician">Musician</option>
<option value="Fighter">Fighter</option>
</div>
</body>
<script>
(function(){
// When the user hovers over the select box,
// it gets the value of the whole list.
('#select_value').hover(function() {
(this).attr('size',('option').length);
},
// When the user stops hovering over the select box,
// it gets back to the normal or default value.
function() {
(this).attr('size', 1);
});
// When the user clicks on the select box,
// it gets the value of the selected item.
('#select_value').click(function() {
$(this).attr('size', 1);
});
});
</script>
</html>
输出: