【问题标题】:Hover effect with image as background以图像为背景的悬停效果
【发布时间】:2014-01-23 15:08:26
【问题描述】:

我不知道是否有办法做到这一点。我有一张图片

 <img src="images/thumb.png" />

这些是该图像的 CSS 属性

float:left;
border:solid 1px #dadada;
margin: 0 5px 0 5px;
padding:5px;
border-radius:4px;
-moz-transition: border 0.2s linear 0s;

现在我想添加一个悬停效果,但是这个悬停效果有一个图像作为背景,如下所示:

    border:solid 1px #888888;
    opacity: 0.4;
    background: url(images/video.png) no-repeat;
    opacity:0.6;
    filter:alpha(opacity=60); /* For IE8 and earlier */

我的问题是悬停效果中的背景图像没有像我想要的那样显示在我的图像顶部。

任何帮助将不胜感激。谢谢

【问题讨论】:

    标签: html css hover


    【解决方案1】:

    您可以将 img 元素包装在一个 div 中,如下所示:

    <div class="background">
        <img src="images/thumb.png" />
    </div>
    

    然后您可以将背景图像应用到 div 元素,而不是悬停状态下的 img 元素。

    你的 CSS 应该是这样的:

    img{
        float:left;
        border:solid 1px #dadada;
        margin: 0 5px 0 5px;
        padding:5px;
        border-radius:4px;
        -moz-transition: border 0.2s linear 0s;
    }
    
    img:hover{
        border:solid 1px #888888;
        opacity:0.4; /* You can remove this line*/
        opacity:0.6;
        filter:alpha(opacity=60); /* For IE8 and earlier */
    }
    div.background{
        background: url(images/video.png) no-repeat;
        height: /* same as your img */
    } 
    

    【讨论】:

    • 你能分享一个链接到你试图实现效果的页面吗?
    • 我的主题尚未上线,但这里是我尝试模拟/复制 Kriesi 的示例。谢谢您的帮助。如果您将鼠标悬停在 Hello World 帖子旁边的图片上。
    • 我没有意识到你正在浮动图像,因此包装 div 元素高度为 0,尝试给包装 div 一些高度,可能你想给它们与 img 相同的高度.我会更新我的帖子
    【解决方案2】:

    这是一个使用 jQuery 的简单方法。您所要做的就是指定hoverImg="",然后脚本会自动完成其余的工作。

    <img src="http://i.imgur.com/vdDQgb.jpg" hoverImg="http://i.imgur.com/Epl4db.jpg">
    
    $('body').find('*[hoverImg]').each(function(index){
        $this = $(this)
        $this.wrap('<div>')     
        $this.parent().css('width',$this.width())  
        $this.parent().css('height',$this.width())
        $this.parent().css('background-image',"url(" + $this.attr('hoverImg')+")")
            $this.hover(function() {
                $(this).stop()
                $(this).fadeTo('',.01)    
            },function() {
                $(this).stop()
                $(this).fadeTo('',1)             
            })                    
    });
    

    在这里试试:http://jsfiddle.net/Diodeus/gYyBL/

    【讨论】:

    • 不是我想要的。这是我要查找的内容的链接 click here 将鼠标悬停在 Hello World 帖子图像上。提前致谢。
    • 这不是一个与 jQuery 相关的问题,另外,这个脚本只是,好吧,不是好的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 2017-11-24
    • 2013-05-07
    • 1970-01-01
    • 2016-12-11
    • 2012-10-31
    相关资源
    最近更新 更多