如何使用jQuery在改变CSS类时触发事件
给定一个带有标题和按钮的HTML文档,当按钮的CSS类发生变化时,jQuery应该触发一个事件。
方法:在jQuery中,没有规定在类的变化上触发一个事件。另一种方法是,当你使用触发器()函数以编程方式改变类时,手动引发一个事件。trigger()函数将引发一个事件,只要按钮的类被改变。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
<style>
.buttonstyle {
background-color: #4CB96B;
color: white;
}
.buttonsize {
padding: 1em;
height: 70px;
width: 400px;
border: .5px solid black;
outline: none;
font-size: large;
border-radius: 10px;
}
</style>
</head>
<body>
<center>
<h1>
Click the button to
change its style
</h1>
<button id="classchange-btn"
class="buttonsize">
Click Me
</button>
</center>
<script>
("#classchange-btn").click(function () {
(this).toggleClass("buttonstyle")
.trigger('classChanged');
});
$("#classchange-btn").on(
"classChanged", function () {
alert("Button Style Change event fired");
});
</script>
</body>
</html>
输出:
最初,该页面看起来像下面的图片。
在点击按钮时,会弹出一条提示信息,表明监听器被触发,按钮的CSS类已经改变。
关闭弹出窗口后,按钮的CSS类别发生了变化(注意绿色背景颜色和白色文本)。
jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。
你可以通过学习这个jQuery教程和jQuery实例,从基础开始学习jQuery。