簡體   English   中英

使用CSS或Jquery將一個圖像淡入另一個圖像

[英]Fade one image into another using css or jquery

我需要能夠在懸停時在初始圖像上方的第二個圖像中淡入淡出。 我需要確保第二張圖像在開始變暗之前不可見 。另一個重要的注意事項是, 任何圖像都不應該在任何時候完全消失 我嘗試了幾種方法,例如使用1張圖片,2張圖片,jQuery動畫和CSS過渡。

我讀過有可能使用jquery為屬性更改設置動畫嗎? 如果這是真的,我該如何使用jquery來動畫化img中src的變化?

$(".image").mouseenter(function() {
        var img = $(this);
        var newSrc = img.attr("data-hover-src");

        img.attr("src",newSrc);
        img.fadeTo('slow', 0.8, function() {
            img.attr("src", newSrc);
        });
        img.fadeTo('slow', 1);
}).mouseleave(function() {
        var img = $(this);
        var newSrc = img.attr("data-regular-src");

        img.fadeTo('slow', 0.8, function() {
            img.attr("src", newSrc);
        });
        img.fadeTo('slow', 1);
});

這就是我目前正在使用的。 這是我最接近的。 但是您會看到不期望的圖像變化。

在背景圖片中使用單個html元素

HTML-沒有比這更簡單的了

<div id="imgHolder"></div>

CSS

#imgHolder {
    width: 200px;
    height: 200px;
    display: block;
    position: relative;
}

/*Initial image*/
 #imgHolder::before {
    content:"";
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    position: absolute;
    background-image:url(http://placehold.it/200x200);
    -webkit-transition: opacity 1s ease-in-out;
    -moz-transition: opacity 1s ease-in-out;
    -o-transition: opacity 1s ease-in-out;
    transition: opacity 1s ease-in-out;
    z-index:10;
}

#imgHolder:hover::before {
    opacity:0;
}

#imgHolder::after {
    content:"";
    background: url(http://placehold.it/200x200/FF0000);
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    position: absolute;
    z-index: -1;
}

演示

或者,如果您想使用圖片標簽...

直接從以下網址竊取: http : //css3.bradshawenterprises.com/cfimg/

HTML

<div id="cf">
  <img class="bottom" src="pathetoImg1.jpg" />
  <img class="top" src="pathetoImg2.jpg" />
</div>

CSS

#cf {
  position:relative;
  height:281px;
  width:450px;
  margin:0 auto;
}

#cf img {
  position:absolute;
  left:0;
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
}

#cf img.top:hover {
  opacity:0;
}

鏈接中還有許多其他示例可以使用,但這可以幫助您入門。

最終不透明度

您已經提到過您不希望初始圖像完全消失。 為此,將opacity:0更改為opacity:0.5或類似的內容。 您需要嘗試使用該值以獲得所需的結果。

最終不透明度為0.8的演示

動態影像尺寸

我認為,如果僅使用CSS,您將被困在兩個映像版本中。 HTML是一樣的。

CSS

#cf {
    position:relative;
}

#cf img {
    -webkit-transition: opacity 1s ease-in-out;
    -moz-transition: opacity 1s ease-in-out;
    -o-transition: opacity 1s ease-in-out;
    transition: opacity 1s ease-in-out;
}

#cf img.bottom {
    z-index:-1;
    opacity:0;
    position:absolute;
    left:0;
}

#cf:hover img.top {
    opacity:0.8;
}

#cf:hover img.bottom {
    display:block;
    opacity:1;
}

演示

暫無
暫無

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

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