2013-05-28 27 views
0

我想將兩個DIV放在彼此的上方,這樣當指針懸停在圖片上方時,頂部的一個會淡出以顯示下方的DIV。我在這裏做了這個:http://quaystreet.chrisloughnane.net/如何確定兩個中心DIV彼此重疊並做出反應?

我想讓它響應,以便圖片可以縮放到移動設備的水平寬度。一張照片沒有問題,但只要我嘗試重新定位下面的DIV就會中斷。

http://jsfiddle.net/chrisloughnane/f2NdQ/4/

是否有可能只用CSS做我想要什麼?

<div id='old'><img src="http://quaystreet.chrisloughnane.net/images/quay-street-old.jpg"/></div> 
<div id='new'><img src="http://quaystreet.chrisloughnane.net/images/quay-street-new.jpg"/></div> 

img { 
    max-width: 100%; 
    display: block; 
    margin: auto; 
} 

回答

3

在這裏,我們走了,

Live Example

CSS:

.images { 
    width: 100%; 
    position: relative; 
    max-width: 354px; 
    margin: 0 auto; 
} 

.images img { 
    position: absolute; 
    top: 0; 
    width: 100%; 
    max-width: 354px; 
} 

的JavaScript:

$(document).ready(function() {  
     $('.images').on('mouseenter', function(){ 
      $('.images .old').fadeOut(1000); 
     }).on('mouseleave', function(){ 
      $('.images .old').fadeIn(1000); 
     }); 
}); 

HTML:

<div class="images"> 
    <img class="new" src="http://quaystreet.chrisloughnane.net/images/quay-street-new.jpg"> 
    <img class="old" src="http://quaystreet.chrisloughnane.net/images/quay-street-old.jpg">  
</div> 

有些事情要你知道:

  1. 每一格在對方我使用的位置絕對的前面。
  2. 我改變了整個事情,你做了div fadeOut,我認爲這種方式更清潔
  3. 我改變你的HTML使用絕對位置。
  4. 您的img寬度爲100%,最大寬度354px可以是任何值,只需要您的img將使用的最大寬度即可。所以當小於354px時,他會使用100%的整個div。

編輯:

如果你不關心browser support你可以使用CSS3過渡,謹防沒有IE Here is the answer with transition

1

的JavaScript是不是真的有必要。你可以用一個平穩過渡CSS3實現相同的行爲

.images { 
    position: relative; 
    margin: 0 auto; 
} 
.images img { 
    position: absolute; 
    top: 0; 
    left: 0; 
    width: 100%; 
    max-width: 354px; 
    -webkit-transition: opacity .8s linear 0s; 
    transition: opacity .8s linear 0s; 
} 
.images img:first-child { 
    z-index: 2; 
} 
.images img:first-child:hover { 
    opacity: 0; 
} 

例如小提琴:http://jsfiddle.net/uNkY5/1/

+0

嘿老兄你的鏈接是等於我 –

+0

@ViníciusMoraes權,只是做了惹我的標籤:) – fcalderan

+0

我想它仍然是錯誤的兄弟 –