单击图像悬停时显示的文本

时间:2014-02-21 16:35:45

标签: javascript jquery html css

我有this jsfiddle

  • 我希望在图片悬停时显示文字(使用.animate)。
  • 当文本显示然后悬停时,用户可以点击它。
  • 当文本和图像都没有悬停时,文字会淡出。
  • 用户不能悬停文字而不先悬停图片。

有人可以帮我这么做吗?

这是我做的:

html:

<div id="container">
    <img src="blabla.jpg" />
    <p id="p1"> click here ! </p>
</div>

jquery:

$(document).ready(function(){
                                        // on img hover
    $("img").hover(function() {
        $(this).next().animate({            // Change p1 style
            'opacity': '1',
            top: "+=10px"},
        200);
                                        // Non hovered   
    }, function() {
        $(this).next().animate({           // Restore p1 style
            'opacity': '0',
            top: "-=10px"},
        200);
    });


    $('#p1').hover(function() {    // On p1 hover
        $(this).next().css({          // change p1 style
            'opacity': '1',
            top: "-51px"});
    }, function() {                // Non hovered
        $(this).next().css({
            'opacity': '0',          // restore p1 style
            top: "-41px"});
    });

});

简单的css:

#container{
    position:relative;
    top: 20px;
    left:20px;
    width:110px;
    height:110px;
}

#p1{
    position:relative;
    color:white;
    width:110px;
    text-align:center;
    margin-left:-55px;
    left:50%;
    background-color: navy;
    height:20px;
    opacity:0;
    top: -129px;
}

1 个答案:

答案 0 :(得分:1)

我只用CSS做过这个。更容易使用(请注意我使用了codepen的前缀免费插件)。

更新:添加了JSFiddle链接

HTML

<div class="box">
  <a href="http://google.co.uk">Click Me!</a>
</div>

CSS

.box{
  background:red;
  width:100px;
  height:100px;
  position:relative;
}

.box:hover a{
  top:10px;
  opacity:1;
}

a{
  -webkit-transition:all .4s;
  -moz-transition:all .4s;
  -o-transition:all .4s;
  -ms-transition:all .4s;
  transition:all .4s;
  background:blue;
  color:#fff;
  position:absolute;
  top:0;
  left:0;
  right:0;
  text-align:center;
  opacity:0;
}

CodePen JSFiddle

请查看Mr. Alien对此更高级版本的评论。

相关问题