jQuery淡入背景图片鼠标悬停时

3
4个回答

4
由于无法仅在块中文本可见时淡化背景,因此您可以进行标记中的小改动:
HTML:
<div class="menuitem"><span></span>ITEM 01</div>

CSS:

.menuitem {
    position: relative;
    /* ... */
}
.menuitem span {
    position: absolute;
    display: none;
    top: 0;
    left: 0;
    width: inherit;
    height: inherit;
    background-image: url(http://thumbs.gograph.com/gg58916312.jpg);
    z-index: -1;
}​

JavaScript:

$(".menuitem").hover(function() {
    $(this).children("span").fadeIn();
}, function() {
    $(this).children("span").fadeOut();
});​

演示: http://jsfiddle.net/JdHWY/11/


你有没有想法为什么当我尝试将jsfiddle粘贴到HTML文件中时它不起作用? http://www.craigzilla.dk/royalarena/menu.html - Craig Jonathan Kristensen
这是一个不错的方法,但可以通过使用:before:after代替span并依赖于CSS3的opacity过渡而不是jQuery来改进。 - Ennui
那为何不使用CSS过渡呢?;) - VisioN

2

HTML:

  <div class="header">
    <div class="menuitem">ITEM 01</div>
    <div class="menuitem">ITEM 02</div>
    <div class="menuitem">ITEM 03</div>
    <div class="menuitem">ITEM 04</div>
  </div>

CSS(层叠样式表):
.menuitem {
    background-image: url(http://thumbs.gograph.com/gg58916312.jpg);
    width: 180px;
    margin-left: 1px;
    margin-right: 1px;
    margin-top: 102px;
    height: 75px;
    float: left;
    cursor: pointer;
    font-size: 36px;
    text-align: center;
    line-height: 85px;
    opacity: 0.5
}

jQuery:

$('.menuitem').hover(function() {
    $(this).stop().animate({
        opacity: 1
    }, 300);
}, function() {
    $(this).stop().animate({
        opacity: 0.5
    }, 300);
});

查看演示


为什么不使用 .stop() 呢? - Roko C. Buljan
这正是我在寻找的,但是否可能只淡化背景图像而不是文本? - Craig Jonathan Kristensen
@CraigJonathanKristensen 我更新了我的代码片段,我认为无法实现背景图像的动画效果。 - thecodeparadox

0

演示 jsFiddle

$('.menuitem').fadeTo(0,0.7).on('mouseenter mouseleave',function( ev ){
    ev=ev.type==='mouseenter'      ?  // event is mouseenter?
    $(this).stop().fadeTo(200,1)   :  // (if yes) 
    $(this).stop().fadeTo(200,0.7) ;  // (if no) event is mouseleave
});

这将非常好地处理多次快速鼠标悬停,感谢.stop()清除动画队列。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接