Jquery/Css问题#2:悬停元素触发不需要的悬停动作

Jquery/Css Issue #2: Hover Elements triggering unwanted hovering action

本文关键字:悬停 不需要 元素 问题 Css Jquery      更新时间:2023-09-26

很久以前,我提出了一个问题的概念:Jquery/CSS挑战,我用Jquery来填充CSS的地方,并给出了悬停功能(因为我以前没有学过,现在非常有用!)所以我复制了代码,编辑到我喜欢的,使我自制的"导航"按钮由span属性(我知道我可以使用按钮,但很好奇它是如何发挥在这里)。

所以当我开始测试它时,我注意到一个奇怪的行为。在我开始对多个"相同"属性进行悬停活动之后。我的鼠标在鼠标悬停时表现得像"悬停",当我离开鼠标时,它表现得像"悬停"。我甚至编辑鼠标进入和鼠标离开从jQuery库,我仍然遇到同样的问题,帮助!

下面是我用于jQuery-Css项目的代码示例:

$(document)
    .ready(
        function() {
            var $span = $("span");
            $span
                .css(
                    {
                        "background-color" : "#eef"
                    }
                )
                .hover(
                    function (){
                        $(this)
                            .css(
                                {
                                    "background-color" : "#ddf"
                                }
                            )
                        ;
                    },
                    function () {
                        $(this)
                            .css(
                                {
                                    "background-color" : "#eef"
                                }
                            )
                        ;
                    }
                )
            ;       
        }
    )
;

然后是用于此场景的适当HTML编码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Jquery Test Page.</title>
        <!--[if lte IE 7]>
            <style>
                .content { 
                    margin-right: -1px;
                } /* this 1px negative margin can be placed on any of the columns in this layout with the same corrective effect. */
                ul.nav a { 
                    zoom: 1;
                }  /* the zoom property gives IE the hasLayout trigger it needs to correct extra whiltespace between the links */
            </style>
        <![endif]-->
    </head>
    <body>
        <div class="menu">
            <span id="a">I am button A</span>
            <span id="b">I am button B</span>
            <span id="c">I am button C</span>
        </div>
    </body>
</html>

我把我的代码只是为了方便编辑的目的,但我需要帮助!感谢大家让这个社区变得很好!

这并不奇怪。这是因为你在悬停事件中创建了两个函数。第一个在你悬停时触发,第二个在你离开按钮时触发。如果你只想要鼠标悬停事件你可以在那里只创建一个函数

$span.css({"background-color" : "#eef"}).hover(function (){
   $(this).css({"background-color" : "blue"});
}); 

并且可以使用jquery中的mouseleave函数来了解用户何时离开按钮。

阅读这篇文章以更好地理解http://www.w3schools.com/jquery/event_hover.asp