簡體   English   中英

jQuery:當圖像懸停時隱藏並顯示div

[英]Jquery: Hide and show a div when image is hover

我想知道是否有人可以幫助我找到將效果懸停在博客中的圖像的解決方案。 我的想法是,當我將鼠標懸停在圖片上時,您會看到一個div,其中包含圖片信息,鏈接項目名稱,日期,...

我所做的是,分配兩個類來做div信息,即類show和類hide ,並且一開始它會以類hide終止。

然后,當img:hover時,使用jQuery / JavaScript刪除類hide並添加類show

問題是,當我將鼠標懸停在圖像上時,會出現所有圖像的信息。

我想知道是否有人可以幫助我使鼠標懸停的圖像信息出現。

我的HTML:

<div id="content">
  <img src="images/1.jpg" alt="Projecto 1" height="290" width="220" />
  <div class="information hide">
      <h2>Titulo</h2>
      <p>Lorem Ipsun</p>
      <a href="#" class="info">Read More</a>
  </div>
</div>

<div id="content">
  <img src="images/1.jpg" alt="Projecto 1" height="290" width="220" />
  <div class="information hide">
      <h2>Titulo</h2>
      <p>Lorem Ipsun</p>
      <a href="#" class="info">Read More</a>
  </div>
</div>

我的CSS:

body div.information {
background: rgba(219, 49, 49, 0.52);
width: 220px;
height: 290px;
position: relative;
top: -290px;
}

/ *懸停效果* /

.hide {
display: none;
}

.show {
display: block;
}

我的JavaScript:

$('img').hover(function() {
    $('.information').addClass("mostrar");
    $('.information').removeClass("hide");      
});

順便說一句,如果有人可以告訴我,當圖像沒有懸停時,如何再次隱藏信息,我非常感謝。

那更簡單的事情呢:

$("div.content > img").hover(function() {
    $(this).next(".information").show(); //hover in
}, function() {
    $(this).next(".information").hide(); //hover out
});

這樣一來,使用jQuery .show.hide你不需要使用您的懸停效果產生的CSS,因為這些jQuery的功能已經采取屬性的照顧。

如果不需要支持IE7及更低版本,則可以使用CSS來使用相鄰的兄弟組合器選擇器,而無需JavaScript:

img + div.information {
    display: none;
}
img:hover + div.information {
    display: block;
}

那就是說:“在img之后立即隱藏div.information ”,但“ img 懸停之后立即顯示div.information ”。 后一個規則既在CSS中出現,也更具體(在我看來 ),它會在圖像懸停時(而不是懸停時)獲勝。

實時示例 -在包括IE8和更高版本的現代瀏覽器中均可使用。

問題是,當我將鼠標懸停在圖像上時,會出現所有圖像的信息。

我相信這是因為您引用的是通用信息類,而不是單個div的ID。 而是使用相鄰的兄弟參考僅獲取您要懸停的圖像的信息。 您可以使用:nth-​​child()選擇器。

$("#content:nth-child(1)")

另外,您不應有多個具有相同ID的div。

$(this).parent().find('.information').addClass("mostrar")
    .removeClass("hide");   

這將獲取要懸停的單個img的父級,在父級中搜索並找到特定於該img的.information

嘗試這個:

$('img').hover(function(){
    $(this).siblings('.information').removeClass('hide').addClass('mostrar').addClass('show');

}, function(){
    $(this).siblings('.information').removeClass('show').removeClass('mostrar').addClass('hide');
});

嘗試這個

$('img').hover(function() {
    $('.information').addClass("hide")
    $(this).next().addClass("mostrar").removeClass("hide");
}, function(){
    $('.information').addClass("hide").removeClass("mostrar")
});

暫無
暫無

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

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