Please take a look at this fiddle
Is this how you would put an if statement in a hover function?
$( ".nn" ).hover(
function() {
if($(this).find('p').height() > $(this).height())
{
$( this ).css( "height","auto" ).removeClass("oh");
}
}, function() {
$( this ).css( "height","6em" ).addClass("oh");
}
);
Since the if statement is only for the first function (mouseover), does the function still trigger on the mouseout function? Is it possible to wrap the if statement around the entire hover function,something like this:
$( ".nn" ).hover(
function() {
if($(this).find('p').height() > $(this).height())
{
$( this ).css( "height","auto" ).removeClass("oh");
}, function() {
$( this ).css( "height","6em" ).addClass("oh");
}
}
);
HTML
Very long text
<div class="nn oh"><p>short text</p></div>
Answers to your questions.
1. Does the function still trigger on the mouseout function?
Yes, because you bound mouseleave event, it will still fire.
2. Is it possible to wrap the if statement around the entire hover function?
No, you can wrap two separate callback functions with the same if
block. You could however take another approach and bind mouseenter
and mouseleave
manually (since hover
is just a sugar for these two events). It would look like this:
$(".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");
}
}
});
But then you would realize that this is not what you need, because in this case you will never get into else
branch, since the condition:
$(this).find('p').height() > $(this).height()
will be false after the mouseenter
event.
Finally . Maybe optimal approach here is to go with just simple CSS without any javascript.
To limit initial block height you would use max-height: 6em
. Then .nn:hover
rule would take care of expansion with max-height: inherit; height: auto;
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.