根据页面长度模糊背景

时间:2016-07-11 11:49:18

标签: javascript jquery css

我试图这样做,如果你向下滚动,会出现一张模糊的图片(带有不透明度),如果你在页面的底部,那么模糊的图片就会完全可见,旧图片会消失。我正在为每个页面使用相同的pagecontainer,我想让这个脚本在每个页面上执行此操作,页面长度不同。

到目前为止,我有这个:

CSS:

.img-src {
    position: fixed;
    background-position: center;
    -webkit-background-size: cover;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: -1;
}

.blurred-img {
    opacity: 0;
}

JS:

var divs = $('.social, .title'),
limit = 0;

$(window).on('scroll', function() {
   var st = $(this).scrollTop();
   if (st <= limit) {
       $('.blurred-img').css({ 'opacity' : (1 - st/limit) });
   }
});

1 个答案:

答案 0 :(得分:1)

filter: blur通常效果很好,看起来更好。这样的事情怎么样?

var img = document.getElementById("background-img");
var container = document.body;
var maxBlur = 20;

window.addEventListener("scroll", function(){
  var position = container.scrollTop / (container.scrollHeight - window.innerHeight);
  // Adjust the position for safari that may scroll higher or lower than the 
  // actual size during their "bounce effect".
  position = Math.max(0, Math.min(1, position));
  var blurAmount = position * maxBlur;
  img.style["filter"] = "blur(" + blurAmount + "px)";
});
#background-img {
  position: fixed;
}
#spacer {
  width: 50px;
  height: 2000px;
}
<img id="background-img"  src="http://placehold.it/400x200?text=Background" />
<div id="spacer"></div>

如果你真的想做你的两个图像策略,我就是这样做的。

var img = document.getElementById("blured-background-img");
var container = document.body;

window.addEventListener("scroll", function(){
  var opacity = container.scrollTop / (container.scrollHeight - window.innerHeight);
  // Adjust the opacity for safari that may scroll higher or lower than the 
  // actual size during their "bounce effect".
  opacity = Math.max(0, Math.min(1, opacity));
  img.style["opacity"] = opacity;
});
#background-img {
  position: fixed;
}
#blured-background-img {
  position: fixed;
  opacity: 0;
}
#spacer {
  width: 50px;
  height: 2000px;
}
<img id="background-img"  src="http://placehold.it/400x200/7A6DFF/D3CFFF?text=Bottom" />
<img id="blured-background-img"  src="http://placehold.it/400x200?text=Top" />
<div id="spacer"></div>

相关问题