2016-07-25 98 views
0

我對編碼有點新。我有一個背景圖像的div。當我向下滾動時,我希望能夠將圖像從其模糊的版本更改爲更清晰的版本。我的HTML代碼是這樣的:滾動時更改圖片

<div class="intro"> 
<div class="blur" style="background-image: url(&quot;blurimage.png&quot;);"></div> 
<div class="clear" style="opacity: 0.00666667; background-image: url(&quot;image.png&quot;);"></div> 
</div> 

我的CSS代碼是這樣的:

.intro{ 
    display: table; 
    width: 100%; 
    height: 700px; 
    position: relative; 

} 
.blur{ 
    position: absolute; 
    top: 0; 
    bottom: 0; 
    left: 0; 
    right: 0; 
    background-attachment: fixed; 
    background-repeat: no-repeat; 
    background-position: center center; 
    background-size: cover; 
    z-index: -10; 
    background-color: #222; 
} 
.clear{ 
    background-size: cover;} 

我已經用很多JavaScript函數,但無濟於事嘗試。請指導我如何使用Javascript功能來做到這一點。 謝謝!

+0

[CSS滾動背景模糊]的可能重複(http://stackoverflow.com/questions/20697004/css-background-blur-on-scroll) – Iceman

回答

0

使用JavaScript,你可以嘗試

document.addEventListener("scroll", function(event) { 
    // this code is executed each time the user scrolls 
    var scrollPosition = window.pageYOffset; 
    // scrollPosition is 0 at the top of the page 
    // it contains how many pixels have been scrolled down 
}); 

希望有所幫助。

+0

無法理解。您能否詳細說明一下示例 –

+0

上面的代碼(在評論中)每次用戶滾動(向上或向下)時執行。 'scrollPosition'變量包含一個值,表示從網站最頂端滾動的像素數。使用此值可以隱藏或顯示其中一個背景圖像,根據滾動位置交換背景圖像。 – kalsowerus

0

添加到您的JS文件(我假設你擁有jQuery的包括在內):

jQuery(document).ready(function($) { 
    scrollPosition = $(document).scrollTop(); 
    $('body').scroll(function() { 
     $('.intro .clear').animate({ 
      height: scrollPosition, 
     }, 300); 
    }); 
}); 

而且它添加到.clear

.clear { 
    position: absolute; 
    top: 0; 
    left: 0; 
    height: 0; 
    background-size: cover; 
} 

也請記住,這個代碼將工作如果你的圖片在頁面頂部。否則,請隨時用父元素的實際選擇器更改$(document).scrollTop()

我也建議使用其他名稱重命名clear類,因爲如果您稍後決定使用CSS框架或插件,那麼該類名可能會保留爲clearfix樣式。

+0

沒有工作bro –

+0

請問您可以發佈一個鏈接來幫助我找出問題所在? – Yoota

0

在這裏看到jsfiddle

取得與改變background-color一個簡單的例子。這是爲了舉例的目的只是因爲

還...你只需要1 intro內的div我不能使用自己的圖像和切換上div.blur.clear,反之亦然,並使用CSS樣式的類。

的想法爲w到你改變取決於滾動

HTML的background,你只有一個div

<div class="intro"> 
    <div class="blur"></div> 
</div> 

CSS:

.intro{ 
    display: table; 
    width: 100%; 
    height: 700px; 
    position: relative; 

} 

.intro div { 
    position: absolute; 
    top: 0; 
    bottom: 0; 
    left: 0; 
    right: 0; 
    background-attachment: fixed; 
    background-repeat: no-repeat; 
    background-position: center center; 
    background-size: cover; 
    z-index: -10; 

} 
.blur{ 
    background-image: url("blurimage.png"); 
    background-color: red; 
} 
.clearimg { 
    background-size: cover; 
    background-color:blue 
    background-image: url("image.png"); 
} 

JQ:

$(window).scroll(function() { 
    if ($(window).scrollTop() > 0) { 
     $(".intro div").addClass("clearimg") 
     $(".intro div").removeClass("blur") 
    }else{ 
     $(".intro div").addClass("blur") 
     $(".intro div").removeClass("clearimg") 
    } 
});