首页 > 解决方案 > 从图像背景到彩色背景的平滑过渡

问题描述

这是我第一次在这个平台上为自己寻求帮助,所以如果我正在寻找的解决方案非常简单,我很抱歉,我是 JS 新手......我正在尝试找到一种从当前背景平稳过渡的方法黑白图像——最浅的“阴影”是#ccc,最暗的是#000——点击按钮即可变为纯色#ccc背景。

所以本质上,我单击一个按钮,然后当前背景转换为纯灰色背景。我设法做到了,但这很突然。

提前致谢。

HTML:

<body id="bd">
.
.
.
   <h2 class="test" onclick="backgroundToGray()" >test</h2>
   <script>
      function change(){
         document.getElementById("bd").style.background='#ccc';
      }
   </script>
.
.
.
</body>

CSS:

html, body {
    background: #ccc;
    background-image: url("background.png");
    background-attachment: fixed;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}

标签: javascripthtmlcss

解决方案


这是一个解决方案,它使用CSS 过渡将背景图像的不透明度淡化为零,从而在下面显示纯色背景。

因为没有 CSS 属性来设置背景图像的不透明度,所以我使用::before 伪元素来保存图像并转换整个元素的不透明度。

这引入了一些小并发症。有关详细信息,请参阅代码注释。

function change(){
  // changed to classList.toggle to add/remove a classname
  // with each click.
  document.getElementById("bd").classList.toggle('grey');
}
#bd {
    height: 90vh; /* just ensuring it occupies enough vertical space for the demo */
    background: #ccc; /* set the solid background color */
    position: relative; /* required for the ::before pseudo-element below to position properly */
}

#bd > * {
  position: relative; /* ensures the content appears on top of the ::before element instead of behind it */
}

#bd::before {
  content: ''; /* required for pseudo elements to render */
  
  /* position the element to cover the entire parent */
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  
  /* set up your bg image here, just as you originally had on #bd */
  /* changed the image url to something that will render on stackoverflow */
  background-image: url("//placekitten.com/400/400");
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  
  /* initially fully opaque so the image is visible */
  opacity: 1;
  
  /* animate the opacity when it changes over 1 second */
  transition: opacity 1s;
}

#bd.grey::before {
  /* when the .grey class is present opacity switches to zero. */
  /* and because of the transition rule above the change is animated */
  opacity: 0;
}
<!-- stripped to its bare minimum just for clarity. no important changes here. -->
<div id="bd">
   <h2 class="test" onclick="change()" >test</h2>      
</div>


推荐阅读