我想用mouseover和mouseleave绑定项目以突出显示我创建的功能。我的脚本不起作用,我不知道自己在做什么错。



$(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/

10-09 19:00