jQuery中悬停函数中的if语句

红巨人

请看看这个小提琴

这是将if语句放在悬停函数中的方式吗?

$( ".nn" ).hover(
  function() {
   if($(this).find('p').height() > $(this).height())
   {
    $( this ).css( "height","auto" ).removeClass("oh");
   }
  }, function() {

    $( this ).css( "height","6em" ).addClass("oh");

  }
);

由于if语句仅用于第一个函数(鼠标悬停),因此该函数是否仍在mouseout函数上触发?是否可以将if语句包装在整个悬停函数周围,如下所示:

    $( ".nn" ).hover(

    function() {
    if($(this).find('p').height() > $(this).height())
    {
       $( this ).css( "height","auto" ).removeClass("oh");

      }, function() {

        $( this ).css( "height","6em" ).addClass("oh");

      }
    }
    );

的HTML

文字很长

<div class="nn oh"><p>short text</p></div>
dfsq

回答您的问题。

1。 Does the function still trigger on the mouseout function?

是的,因为您绑定了mouseleave事件,它仍然会触发。

2。 Is it possible to wrap the if statement around the entire hover function?

不,您可以在同if一块中包装两个单独的回调函数但是,您可以采用另一种方法并进行绑定mouseentermouseleave手动操作(因为hover这只是这两个事件的主要内容)。它看起来像这样:

$(".nn").on('mouseenter mouseleave', function(e) {
    if ($(this).find('p').height() > $(this).height()) {
        if (e.type == 'mouseenter') {
            $(this).css("height", "auto").removeClass("oh");
        }
        else {
            $(this).css("height", "6em").addClass("oh");
        }
    }
});

但是您会意识到这不是您所需要的,因为在这种情况下,您将永远不会进入else分支,因为这种情况:

$(this).find('p').height() > $(this).height()

mouseenter事件发生后将为假


终于也许这里的最佳方法是只使用简单的CSS,而不使用任何javascript。

要限制初始块的高度,可以使用max-height: 6em然后.nn:hover规则会考虑用扩展max-height: inherit; height: auto;

.nn {
    border-bottom: 0.8em solid #B1B3BE;
    font-size: 25px;
    max-height: 6em;
    margin: 6% 0;
    background: #eee;
    padding: 3%;
    border-bottom: 0.3em solid #6F87B3;
    width:40%;
    display:block;
    overflow: hidden;
}
.nn:hover {
    max-height: inherit;
    height: auto;
    overflow: auto;
}
<div class="nn oh">
    <p>ddddddddddddd dsffffffffff fffffffff dffffff ffff fgdgfdfgddfg ffgdfdgdfgdfg dfggdfdgfd fdsdgfdfgdgf fdgfdgf gf</p>
</div>
<div class="nn oh">
    <p>ddddddddddddd</p>
</div>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章