【问题标题】:Logic for hovering in jQuery dependent on where mouse hovers在 jQuery 中悬停的逻辑取决于鼠标悬停的位置
【发布时间】:2011-05-12 15:18:55
【问题描述】:

我试图弄清楚如何在 jQuery 中编写一个关于用户将鼠标悬停在何处的条件语句。

我已经掌握了悬停功能的逻辑。当用户将鼠标悬停在列表项“Z”上时,页面上的另一个元素(具有类“box”的 div)执行一个功能(即动画)。但是在等式的悬停“out”部分(悬停在列表项“Z”之外),我需要按照以下几行编写条件语句:

  • 当悬停在列表项“Z”之外时,如果用户随后将鼠标移动到 div“.box”上,则运行函数 A
  • 如果用户没有将鼠标移到 div ".box" 上,则运行函数 B

希望这已经足够清楚了。本质上,我试图确定用户接下来悬停的位置并相应地执行功能。

【问题讨论】:

  • 为什么不使用 mouseenter/mouseleave 或 mouseover/mouseout ?
  • 感谢您的回复。我想我仍然不确定如何使用鼠标悬停/鼠标悬停来编写这种情况的逻辑。我已经查看了这些事件的文档,但不清楚如何在这种情况下实现它们。

标签: jquery


【解决方案1】:

如果你有这样的html:

<ul id="someList">
    <li>some list item 1</li>
    <li>some list item 1</li>
    <li>some list item 1</li>
</ul>

您可以像这样实现所需的功能:

$("ul#someList > li").mouseover(function(){
    // the next line will set the background of the hovered element to red
    $(this).css({background: "red"});
}).mouseout(function(){
    // the next line will set the background of the list element to green when the mouse is out
    $(this).css({background: "green"});
});

编辑:我认为这会更容易理解

var mouseOverHandler = function() {

    var styleObject = {
        background: "red"
    };

    $(this).css(styleObject);
}

$("ul#someList > li").mouseover(mouseOverHandler);

【讨论】:

  • 嘿Teneff...感谢您的回复。实际上我试图做的有点不同。我想我可能需要改写一下,让它更清楚一点。
猜你喜欢
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-07
  • 2011-11-13
  • 1970-01-01
相关资源
最近更新 更多