第二个函数的jQuery悬停问题(mouseout)

时间:2014-03-06 10:48:11

标签: javascript jquery html css

在鼠标移出时出现.hover()问题。似乎没有用。它适用于淡入淡出,但不会出现。我基本上在另一个图像上消失了。 'clone'有一个较低的z-index开始,我把它带到前面,然后在悬停时淡入它。两张图片都堆叠在一起。

小提琴:http://jsfiddle.net/C6AfM/

JavaScript:

$.fn.hoverImage = function() {
    //add event handler for each image (otherwise it will add the same event handler for all images all at once)
    this.each(function() {
        var img = $(this);
        var magnifyImage = img.next();

        //hover: first function is for mouseover, second is on mouseout
        img.hover(function() {
            magnifyImage.css("z-index", 2).animate({
                opacity:0.8         
            }, 200);
        }, function() {
            magnifyImage.css("z-index", -200).animate({
                       opacity:0
                    }, 200);
        });
    });
}

HTML:

<span class="img-span">                                
    <img src="(url)" class="project-img">                                                                    
    <img src="(url)" class="project-img-clone">                                                                    
    <figcaption>Caption</figcaption>
</span>

CSS:

.img-span {
    width:27.08333333333333%; /* 260 / 960 */
    margin-right:3.009259259259259%; /* 26 / 864 */
    display:inline-block;
    vertical-align: top; 
    position:relative;
}

.project-img {
    max-width:100%;
}

.project-img-clone {
    position:absolute;
    top:0;
    left:0;
    max-width: 100%;
    z-index:-200;
    opacity:0;
}

1 个答案:

答案 0 :(得分:2)

问题是因为克隆出现了mouseleave未在原始图像中触发,它被克隆触发

$.fn.hoverImage = function() {
    //add event handler for each image (otherwise it will add the same event handler for all images all at once)
    this.each(function() {
        var img = $(this);
        var magnifyImage = img.next();
        console.log(magnifyImage);

        //hover: first function is for mouseover, second is on mouseout
        img.add(magnifyImage).hover(function() {
            magnifyImage.css("z-index", 2).animate({
                opacity:0.8         
            }, 200);
        }, function() {
            magnifyImage.css('opacity', 0);
        });
    });
}

演示:Fiddle


或使用pointer-events - IE9 +

.project-img-clone {
    position:absolute;
    top:0;
    left:0;
    max-width: 100%;
    z-index:-200;
    opacity:0;
    pointer-events: none;
}

演示:Fiddle