根据页面长度模糊背景

Blur background based on page length

本文关键字:模糊 背景      更新时间:2023-09-26

我正在尝试使以下情况:如果您向下滚动,会出现模糊的图片(不透明),如果您在页面底部,模糊的图片完全可见,而旧的图片消失了。我为每个页面使用相同的页面容器,我想让这个脚本在每个页面上都这样做,具有不同的页面长度。

到目前为止,我有这个:

.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) });
   }
});

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>