2016-07-25 100 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") 
    } 
});