0

我正在尝试做一些事情,我昨天才开始阅读有关 jQuery 的内容,所以对我来说还不太顺利:)

但是,我要做的是在 mouseenter/leave 或 hover 上交换我的徽标图像,这取决于更好的...

所以这是我做的,它肯定很糟糕,但是......

    $(document).ready(function() {
    var logo = $('#logo');

    logo.on('mouseenter', function() {
        logo.css('background-image', 'url("img/logo2.png")');
    });
    logo.on('mouseleave', function() {
        logo.css('background-image', 'url("img/logo.png")');
    });
});

这很好用,它可能也不是很好的代码......但是没有像fadeIn和fadeOut这样的动画......我不知道如何制作它。

请帮我做这个,并在此先感谢!

4

3 回答 3

1

In order to fade in the image you will have to load both images to begin with, one on top of the other with absolute positioning and appropriate z-index.

Then you just have to make the image 'on-top' fade-out when you hover over it, to reveal the one underneath. So you never actually have to adjust the background-image of the element.

<div id="logo-container" style="position:relative;">
    <div id="logo-above" style="position:absolute;z-index:2">
        <img src="img/logo1.png" />
    </div>
    <div style="position:absolute;z-index:1">
        <img src="img/logo2.png" />
    </div>
</div>

<script>
    $(document).ready(function() {
        var $logoContainer = $('#logo-container');
        var $logoAbove = $('#logo-above');

        $logoContainer.on('mouseenter', function() {
            $logoAbove.fadeOut();
        });
        $logoContainer.on('mouseleave', function() {
            $logoAbove.fadeIn();
        });
    });
</script>

p.s. its good practice to prefix variables that are 'jqueryfied' with $ so you know not to call jquery on them again. eg $logoContainer.

于 2012-09-04T22:26:19.453 回答
1

您可以使用CSS3 过渡来交叉淡入淡出。只需将 -vendor-transition 属性添加为 CSS:

#logo
{ 
    background: url('img/logo.png');
    -webkit-transition: all 1s ease;
}

演示

于 2012-09-04T22:29:37.860 回答
1

Have a look at this DEMO.

Instead of editing one image's CSS, this technique changes the layering of two images.

Here's the JS:

var $img1 = $('#image1'),
    $img2 = $('#image2');

$('#logo').on('mouseenter', function() {
    $img1.stop(true, true).prependTo(this).show();
    $img2.fadeOut();
}).on('mouseleave', function() {
    $img2.stop(true, true).prependTo(this).show();
    $img1.fadeOut();
});​
于 2012-09-04T22:29:39.723 回答