index.html:
<html>
<head>
<title>chapter 5</title>
<script src="jquery.js"></script>
<script src="app.js"></script>
</head>
<body>
<div >
<p>this is a paragraph</p>
</div>
</body>
</html>
应用程序.js:
$(function() {
$("div").on("hover", function(event) {
if(event.type === "mouseenter") {
$(this).css("background", "blue");
}
else {
$(this).css("background", "red");
}
});
});
所以根据我的 Jquery:当我将鼠标移到标签上时,它应该将其颜色更改为红色,而当除鼠标输入之外的任何其他甚至内部标签时,它应该更改为蓝色。但是什么也没发生?
我已经尝试过事件的其他功能,效果相当好我不明白为什么这个不起作用我是否必须用“css”做点什么?
最佳答案
来自 jQuery 的 .on()
方法文档:
Deprecated in jQuery 1.8, removed in 1.9: The name
"hover"
used as a shorthand for the string"mouseenter mouseleave"
. It attaches a single event handler for those two events, and the handler must examineevent.type
to determine whether the event ismouseenter
ormouseleave
. Do not confuse the"hover"
pseudo-event-name with the.hover()
method, which accepts one or two functions.
监听 mouseenter
和 mouseleave
事件而不是 hover
:
$("div").on("mouseenter mouseleave", function(event) {
$(this).css("background", event.type === "mouseenter" ? "blue" : "red");
});
或者,您可以将对象传递给 .on()
方法:
$("div").on({
mouseenter: function() {
$(this).css("background", "blue");
},
mouseleave: function() {
$(this).css("background", "red");
}
});
关于javascript - Jquery "the event object"试图更改 <div> 标签的 "CSS"不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20830433/