javascript - Jquery "the event object"试图更改 <div> 标签的 "CSS"不起作用

标签 javascript jquery html css

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 examine event.type to determine whether the event is mouseenter or mouseleave. Do not confuse the "hover" pseudo-event-name with the .hover() method, which accepts one or two functions.

监听 mouseentermouseleave 事件而不是 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/

相关文章:

jquery脚本来监控disqus评论添加?

javascript - 在 PHP 中的所有页面上包含 header

javascript - 如何在 <form>...</form> 中改变样式

javascript - 提交按钮按条件在函数中向上 float

javascript - Bootbox.js 正在向上滚动窗口

javascript - 使用javascript和css拖动

javascript - 解析谷歌警报提要

javascript - Basic Jquery Slider(我认为是脚本问题)

Javascript:需要注册表单帮助

javascript - 使用 xhr-mock 测试 AJAX 函数失败