我想用 mouseover 和 mouseleave 绑定(bind)元素以突出显示我创建的功能。我的脚本不起作用,我不知道我做错了什么。
$(function() {
$("#evtTarget").bind("mouseover", highlight);
$("#evtTarget").bind("mouseleave", highlight);
});
function highlight(evt) {
$("#evtTarget").toggleClass(highlighted);
}
.normal {
width: 300px;
height: 200px;
background-color: Yellow;
font-size: 18pt;
}
.highlighted {
background-color: Red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Binding and Unbinding Events with jQuery</title>
</head>
<body>
<h1>Binding Event Example</h1>
<div id="evtTarget" class="normal">Mouse over this div to see the effect. Click on it to unbind the mouseover.</div>
</body>
</html>
最佳答案
你差一点,你忘了 ""
在 $("#evtTarget").toggleClass(highlighted);
应该是$("#evtTarget").toggleClass("highlighted");
演示
function highlight() {
$("#evtTarget").toggleClass("highlighted");
}
$(function() {
$("#evtTarget").bind("mouseover", highlight);
$("#evtTarget").bind("mouseleave", highlight);
});
.normal {
width: 300px;
height: 200px;
background-color: Yellow;
font-size: 18pt;
}
.highlighted {
background-color: Red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Binding Event Example</h1>
<div id="evtTarget" class="normal">Mouse over this div to see the effect. Click on it to unbind the mouseover.</div>
关于javascript - 如何使用 toggleClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56129148/