【问题标题】:Background size transition effect doesn't work on nth-child背景大小过渡效果不适用于第 n 个孩子
【发布时间】:2015-12-04 21:50:31
【问题描述】:

我尝试在下面的代码中添加 nth-child 以将不同的背景图像应用于每个 div。

标记之前尝试:

<div class="coldiv">
    <div class="hoverimg">
        <!-- Contents 1 --> 
    </div>
</div>

<div class="coldiv">
    <div class="hoverimg">
        <!-- Contents 2 --> 
    </div>
</div>

CSS:

.coldiv {
    width:33.3%;
    padding:5px;
    float:left;
}

.hoverimg { 
    width:100%;
    height:200px;
    overflow:hidden;
    position:relative;
    cursor:pointer;
    transition:all 0.4s ease;
    background:url(../img/bg_btn1.jpg) center center no-repeat;
    background-size:620px 200px;
}
.hoverimg.on {
    background-size:680px 219px;
}

我使用 addClass 来添加 .on 类,效果很好。

但是当我添加 nth-child 伪类时

.coldiv:nth-child(1) .hoverimg { background:url(../img/bg_btn1.jpg) center center no-repeat; }

并从.coldiv { ~ } 中删除背景属性,然后过渡不起作用。

我也尝试将 id 放在每个 div 而不是 nth-child 上,但同样的事情发生了。

【问题讨论】:

  • 我认为您遇到问题的原因是因为当您使用伪第 n 个孩子时,没有发生过渡。相反,它只是覆盖了 .hoverimg 类。另外,当您可以使用 .hoverimg:hover css 时,为什么还要使用 addClass?看看这个,也许它会帮助解决问题jsfiddle.net/benneb10/6sh6fmcb
  • @Benneb10 我找到了解决方案。无论如何谢谢你:)

标签: jquery html css


【解决方案1】:

没关系。我找到了解决方案:)

我像这样分离了属性,它工作正常:

background-position:center center;
background-size:620px 200px;

【讨论】:

    【解决方案2】:

    改变你的风格过渡适合你

    .hoverimg { 
        width:100%;
        height:200px;
        overflow:hidden;
        position:relative;
        cursor:pointer;
        transition:width 0.4s ease;
        background-size:620px 200px;
         background:url("../img/bg_btn1.jpg") center center no-repeat; 
    }
    .coldiv:hover .hoverimg {
        background-size:680px 219px;
    }
    

    【讨论】:

    • 谢谢。我也试试这个:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    相关资源
    最近更新 更多