簡體   English   中英

帶切換的jQuery懸停功能不起作用

[英]jQuery hover function with toggle not working

我有以下代碼應該用來切換div和p的背景,但事實並非如此,我也不知道為什么。 你能幫忙嗎?

jQuery的

$(document).ready(function(){
    $("div.portfolio-img").hover(
        function(){
            $(this).toggleClass(".portfolio-img-hover");
            $(this).find("h5.excerpt-title").toggleClass(".excerpt-title-hover");
            $(this).find("p.portfolio-excerpt").toggleClass(".portfolio-excerpt-hover"); 
        }
      )
});

的HTML

<div class="portfolio-img">
    <a href="#single_project"><img src="images/thumbnail.jpg"/></a>
    <h5 class="excerpt-title">First Title</h5>
    <p class="portfolio-excerpt">Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum                Lorem ipsum Lorem ipsum</p>
</div>

的CSS

h5.excerpt-title{
    margin:30px 0px 5px;
    transition:background-color 0.5s ease;
}

.excerpt-title-hover{
    opacity:1;
    color: #ed0b0b;
}

.portfolio-excerpt-hover{
    opacity:1;
    background:#e2e2e2;
}

.portfolio-img-hover{
    opacity:1;
    background:#e2e2e2;
    border-bottom:2px solid #ed0b0b;
}

.portfolio-img{
    width:220px;
    display:inline-block;
    padding:15px 5px;
    margin:0px 5px 10px;
    opacity:0.6;
    border-bottom:1px solid grey;
    transition:background-color 0.5s ease;
    background-color:#ffffff;
}

此處的jsfiddle: http : //jsfiddle.net/a12b0u0k/

$(this).toggleClass("div.portfolio-img-hover");

div.portfolio-img-hover是一個選擇器。 您只需要portfolio-img-hover

toggleClass將添加/刪除您在()中添加的所有內容,並且您要添加portfolio-img-hover而不是div. 部分。

使用切換類方法時,應僅包含類名,如下所示。 您還應該將$(this)存儲在變量中。

$(document).ready(function(){
  $("div.portfolio-img").hover(function(){
    var $this = $(this);
    $this.toggleClass("portfolio-img-hover");
    $this.find("h5.excerpt-title").toggleClass("excerpt-title-hover");
    $this.find("p.portfolio-excerpt").toggleClass("portfolio-excerpt-hover"); 
  })
});

另外,您要確保CSS的“懸停”類樣式低於默認樣式,並且還應該包括原始選擇器。

看到這里http://jsfiddle.net/a12b0u0k/1/

將您的jQuery更改為此:

$(document).ready(function(){
   $("div.portfolio-img").hover(function(){
         $(this).toggleClass("portfolio-img-hover");
         $(this).find("h5.excerpt-title").toggleClass("excerpt-title-hover");
         $(this).find("p.portfolio-excerpt").toggleClass("portfolio-excerpt-hover"); 
      }
   );
});

並在.portfolio-img-hover{}交換.portfolio-img-hover{}.portfolio-img-hover{} portfolio-img{}上的位置。

在這里嘗試: jsFiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM