我想用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>
发布于 2019-05-14 11:17:41
你差点就把""忘在$("#evtTarget").toggleClass(highlighted);上了
应该是$("#evtTarget").toggleClass("highlighted");
Demo
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>
发布于 2019-05-14 11:17:26
逻辑的问题在于,需要将highlighted作为字符串提供给toggleClass()方法:
$(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>
<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>
尽管如此,这里绝对不需要任何JS或jQuery,因为在CSS中使用:hover伪选择器可以更有效地(而且性能更好)实现相同的效果:
.normal {
width: 300px;
height: 200px;
background-color: Yellow;
font-size: 18pt;
}
#evtTarget:hover {
background-color: Red;
}<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>
如果要实现div文本中指出的行为,在单击div本身时禁用悬停行为,则可以向元素中添加一个类,然后使CSS规则足够具体,以便:hover不覆盖它,如下所示:
$('#evtTarget').click(function() {
$(this).addClass('disable-hover');
});.normal {
width: 300px;
height: 200px;
background-color: Yellow;
font-size: 18pt;
}
#evtTarget:hover {
background-color: Red;
}
#evtTarget.disable-hover {
pointer-events: none;
}<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>
https://stackoverflow.com/questions/56129148
复制相似问题