【问题标题】:jQuery mouseover not working as intendedjQuery mouseover 无法按预期工作
【发布时间】:2012-06-21 02:21:15
【问题描述】:

这是我的html:

<div id="social">
    <a href="#" class="twitter"><span class="text">Twitter</span></a>
</div>

我打算做的是最初隐藏 span.text 以及当我将鼠标悬停在 div 背景中的图像上时。这是我的css

#social a {
    display:inline-block;
    overflow:hidden;
    padding:4px 0 0 28px;
/* left padding is for the bg image to be visible*/
}
#social a span {
    display:none;
}
#social .twitter {
    background:url(../images/social/twitter.png) no-repeat left top;
}
#social .twitter:hover {
    background:url(../images/social/twitter_hover.png) no-repeat left top;
}

这是我的 js:

$("#social a.twitter").mouseover(function(){
  $("span",this).show("slow");
}).mouseout(function(){
  $("span",this).hide("slow");
});

但是当我将鼠标悬停在图像上时会发生什么,它一直显示和隐藏文本。我哪里出错了?

【问题讨论】:

标签: jquery mouseover


【解决方案1】:

你有一个很常见的问题,当 span 显示时,鼠标不再在 a 上,所以 mouseout 事件被调用。

使用 mouseenter 和 mouseleave 事件来解决这个问题

$("#social a.twitter").mouseenter(function(){
  $("span",this).show("slow");
}).mouseleave(function(){
  $("span",this).hide("slow");
});​

fiddle for you :D

并且,在 css 中,cmets 使用 /* */ 而不是 //

【讨论】:

  • 太棒了!按预期工作......另一个教训:) 谢谢
  • 不客气。在我找到它之前,我很头疼。我建议您阅读有关 mouseenter 和 mouseleave 的文档。
  • 再问一个问题...解决方案工作正常,但是当我将鼠标悬停在图像上时,文本会立即显示。 hide 函数将文本滑动到底角,但不是 mouseenter 函数。如何使 mouseenter 函数也可以在文本中滑动?
【解决方案2】:

在您的 CSS 中:

// left padding is for the bg image to be visible

// 不是 cmets 的有效符号。

它们必须用/* */ 包裹起来,例如:

/* left padding is for the bg image to be visible */

【讨论】:

  • 是的,很抱歉。我只为这篇文章添加了评论。
【解决方案3】:

您不需要(也不应该)使用 javascript 来实现此效果。你可以用 CSS 来做,它更干净,更语义化:)。示例:

​a.twitter {
    display: block;
    width: 300px;
    height: 300px;
    background: url('http://www.simplyzesty.com/wp-content/uploads/2012/01/twitter_newbird_boxed_whiteonblue2.png');
}

a.twitter span {
    opacity: 0;
    -webkit-transition: opacity 0.2s;
    -moz-transition: opacity 0.2s;
    -o-transition: opacity 0.2s;
    transition: opacity 0.2s;
}

a.twitter:hover span {
    opacity: 1;
}

jsFiddle:http://jsfiddle.net/Ut4Gx/

【讨论】:

  • 对不起,我想我没有清楚地解释自己。最初只有 twitter 图标可见,当您悬停时,我希望文本滑入,即图标应该向左移动以显示文本。
【解决方案4】:

尝试使用mouseleave。重新鼠标移出:

由于事件冒泡,这种事件类型可能会引起很多麻烦。为了 例如,当鼠标指针移出 Inner 元素时 这个例子,一个mouseout事件将被发送到那个,然后涓涓细流 到外。这可能会在不合时宜的情况下触发绑定的 mouseout 处理程序 次。请参阅 .mouseleave() 的讨论以获取有用的替代方法。

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 2023-04-03
    • 2012-05-19
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多