如何在jQuery中为元素附加一个以上的事件处理程序
在事件处理程序的帮助下,我们可以在HTML元素上设置jQuery中可用的特定事件。在jQuery中,有许多可用的事件,如click(), mouseover(), dblclick()等。在这篇文章中,我们将学习如何在元素上附加一个以上的事件处理器。在jQuery中,我们可以轻松地在任何元素上添加一个或多个事件处理器。
例子:在这个例子中,我们将在一个div上添加三种不同的事件处理程序,并分别检查所有的事件。第一个事件是click(),当我们点击div时,它将缩小;第二个事件是dblclick(),当我们双击div元素时,它将变大;第三个事件是mouseover,当我们将指针移到div时,它将改变颜色。所以这就是我们如何在一个div元素上实现三个不同的事件处理程序。
<!DOCTYPE html>
<html lang="en">
<head>
<!-- jQuery CDN link -->
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<style>
/* Required css code */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
background-color: rgb(32, 32, 32);
}
.main {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
#shape {
height: 200px;
width: 200px;
background-color: green;
border-radius: 100%;
margin: 100px;
}
</style>
</head>
<body>
<!-- Shape is inscribed in main container -->
<div class="main">
<div id="shape"></div>
</div>
<script>
// Required jQuery code
(document).ready(function() {
("#shape").click(function() {
(this).animate({
height: "50px",
width: "50px"
});
});
("#shape").dblclick(function() {
(this).animate({
height: "300px",
width: "300px"
});
});
("#shape").mouseover(function() {
$(this).css("background-color", "white");
});
});
</script>
</body>
</html>
输出: