如何在jQuery中使用.on和.hover
jQuery .on()方法:该方法用于附加事件监听器到一个元素。这个方法等同于vanilla JavaScript中的addEventListener。
语法:
$(element).on(event, childSelector, data, function)
参数
- event。它指定了要附加的事件(点击、提交等)。
- childSelector。这是一个可选的参数,它指定了特定的孩子,给定的事件处理程序可以被使用。
- data。它指定了与函数一起传递的可选数据。
- function。它指定了所附事件触发时要运行的函数。
示例:
<!DOCTYPE html>
<html>
<head>
<!-- Adding jQuery Library -->
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js">
</script>
<style>
/* Adding basic styling */
div {
background-color: green;
width: 100px;
height: 100px;
color: #fff;
text-align: center;
}
</style>
</head>
<body>
<div>Normal</div>
<script>
('div').on('click', function () {
// Changing the content
(this).html('Clicked!');
});
</script>
</body>
</html>
输出:
- 在点击div元素之前。
- 点击div元素后。
jQuery .hover()方法:该方法用于指定元素在mouseover和mouseout条件下的样式。它需要两个函数作为一个参数。
- mouseoverFunction。当鼠标进入该元素时触发。
- mouseoutFunction。当鼠标离开元素时触发。
你可以在这些函数中指定多个样式。
语法:
$(element).hover(mouseoverFunction, mouseoutFunction)
示例:
<!DOCTYPE html>
<html>
<head>
<!-- Adding jQuery Library -->
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js">
</script>
<style>
/* Adding basic styling */
div {
background-color: green;
width: 100px;
height: 100px;
color: #fff;
text-align: center;
}
</style>
</head>
<body>
<div>Normal</div>
<script>
('div').hover(function () { // mouse-in
(this).css("background-color", "blue");
(this).html('Hovered!');
},
function () { // mouse-out
(this).css("background-color", "green");
$(this).html('Normal');
}
)
</script>
</body>
</html>
输出:
- 鼠标移过去之前。
- 鼠标移过去之后。