【问题标题】:adding class using jQuery not showing the effects使用jQuery添加类不显示效果
【发布时间】:2013-12-16 11:12:53
【问题描述】:

我有一个 HTML 如下:

<div class="container">
      <!-- Example row of columns -->
      <div class="row">
        <div class="span7">
          <div class="home-image left-image">
            <img class="photography-left-top" src="http://placehold.it/700x440" />
            <p class="image-text_left">Wedditng Photography</p>
          </div>

          <h5>Heading</h5>
        </div>
        <div class="span5">
            <div class="home-image right-image right-image-top">
                <img class="photography-right-top" src="http://placehold.it/400x200" />
                <p class="image-text_right-top">Fashion Photography</p>
          </div>
          <div class="home-image right-image right-image-bottom">
            <img class="photography-right-bottom" src="http://placehold.it/400x200" />
            <p class="image-text_right-bottom">Contact</p>
          </div>

          <h5>Heading</h5>
       </div>

      </div>

 </div>        

还有 CSS :

.home-image {
    position:relative;
}
.photography-left-top,.photography-right-top,.photography-right-bottom {
    position : absolute;
}
.image-text_left {
    display:none;
    position:absolute;
    width:300px;
    top:200px;;
    left:200px;
    z-index : 100;
    font-weight:bold;
}
.image-text_right-top,.image-text_right-bottom {
    display:none;
    position:absolute;
    width:300px;
    top:100px;
    left:100px;
    z-index : 100;
    font-weight:bold
}
.right-image-bottom {
    margin-top:220px;
    position:relative
}
.right-top {
    position:relative
}
.home-img-hover {
    background:#911717;
}

JS:

$(document).ready(function(){

        $(".left-image").hover(function () {
            $(this).find('.photography-left-top').fadeTo('slow',0);
            $(this).addClass('home-img-hover');
            $('.image-text_left').show();
        },
        function () {
            $(this).find('.photography-left-top').fadeTo('400',1.0);
            $('.image-text_left').hide();
        });

由于addClass('home-img-hover') 会将a 类添加到当前class,所以当我将鼠标悬停在left-image 上时,我期待背景颜色。但它显示白色默认背景。为什么?

Sample in JSFiddle

【问题讨论】:

  • .home-img-hover DIV 高度等于 0
  • 因为你使用了 .fadeTo('slow', 0);表示该项目不可见,因此您看不到元素上的任何样式。

标签: jquery html css class addclass


【解决方案1】:

它完全符合您的预期,您只是看不到它,因为.home-image 没有高度,因为其中的所有内容都脱离了正常的文档流(使用position:absolute)。试着给.home-image 一些尺寸,你就会明白我的意思了:

.home-image {
    position:relative;
    width:400px;
    height:240px;
}

JSFiddle

【讨论】:

    【解决方案2】:

    这是你的问题,你的 div 的高度实际上是0px

    只需添加

    height: 240px;
    width: 400px;
    

    .home-image 类,你会看到你的代码确实有效。

    updated JSFiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      相关资源
      最近更新 更多