开发者

Very strange jquery mouseleave behavior

I have two divs stacked one above the other, with my code expanding the boxes when your mouse hovers on a div. When you remove your mouse from the div, the div shrinks back to the original size.

My code works just fine and dandy when you swipe the mouse into a div and then out of a div into the blank area of the page. However, if you try moving the mouse between the two divs, everything goes haywire, and now the correct boxes no longer shrink and the overall functionality is lost.

Here is my code:

$(".divbox1").hover(function() {    
var height = $(this).height();
var height2 = $(this)[0].scrollHeight;

if (height2 > 35) {

    //Current position in relation to the page
    var offsetTop = $(this).offset().top;
    var offsetLeft = $(this).offset().left;

    //Clone the code and attach it to the page
    $(this).clone().css({
        position: "absolute",
        top: offsetTop,
        left: offsetLeft
    }).attr("id", "cloned").appendTo("body");

    //Hide the code underneath
    //$(this).css("visibility", "hidden");

    $('#cloned').animate({
    开发者_开发百科    height: height2
    }, 150).bind('mouseleave', function() {
        var cloned = $(this);
        //Animate back and remove
       cloned.animate({
            height: height
        }, 300, function() {
            cloned.remove();
            //Show the code underneath
            //$(this).css("visibility", "visible");
        });


    });
}
 });

And this my associated HTML and CSS

    .divbox1 {
color: #100;
background-color: #f9f9f9;
border: 1px solid silver;
overflow: hidden;
width: 200px;
height:35px;
}

    <div class="divbox1" id="one">
sdsdsadasdsad<br />
sadasdsdaasdadsadssdsdsadasasdasdsdsddsasdasdasdasdasddasadsasd<br>
dasdasasdasdsad
<br /><br />
Really Tall box!
    </div>
   <br />
    <div class="divbox1" id="two">
  Second box<br />
yada ydad<br />
yada yada<br />
yada yada<br />
    </div>

For those interested, the project is also on Jsfiddle: http://jsfiddle.net/hQkFH/10/

Also incase anyone was wondering why I cloned the box before animating, its because I wnt the open box to overwrite anything on the page underneath it (in the case of the top box, the second box)

Thank you!


Have you tried adding $('#cloned').remove(); before cloning the divbox?

I think the problem is that you end up with two divs with id="cloned" when you enter in both hover events


This problem occurs when the user enters the first div while the second is still animated (so there is already a 'cloned' element in the page).

Here is a workaround with an animation variable (boolean) : http://jsfiddle.net/hQkFH/14/

It fixes the bug, but when the user enters the first div while the second is still animated, it does nothing (but if he comes back to the first div again, it will open normally)


Use .stop(true, true) to clear the animation queue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜