【问题标题】:Change background color on click and drag单击并拖动更改背景颜色
【发布时间】:2020-05-04 17:50:54
【问题描述】:

我正在尝试创建一个网站,当您单击并拖动它时,背景颜色会发生变化。问题是背景颜色在我的代码中确实更新了,但它没有那种平滑一致的平滑渐变效果。它只是在您拖动时从一种颜色跳到另一种颜色。

在这段代码中我想要的效果是通过mousemove事件监听器实现的:

document.addEventListener('mousemove', function(event) {
  var width = window.innerWidth / 255
  var height = window.innerHeight / 255
  var xValue = event.clientX / width;
  var yValue = event.clientY / height;
  document.getElementById("bg").style.backgroundColor = 'rgb(' + yValue + ',' + yValue + ',' + xValue + ')';
});
* {
  padding: 0;
  margin: 0;
}

body {
  background-color: white;
  height: 100vh;
  width: 100%;
}
<body id="bg">
  <div></div>
</body>

【问题讨论】:

    标签: javascript css dom css-transitions


    【解决方案1】:

    根据page,您无法使用 CSS 转换背景渐变。他提供了一种可能的解决方案,以借助伪元素和不透明度变换来实现该效果。

    .gradient {
      position: relative;
      background-image: linear-gradient(
        to right,
        hsl(211, 100%, 50%),
        hsl(179, 100%, 30%)
      );
      z-index: 1;
      height: 100px;
    }
    
    .gradient::before {
      position: absolute;
      content: "";
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      background-image: linear-gradient(
        to bottom,
        hsl(344, 100%, 50%),
        hsl(31, 100%, 40%)
      );
      z-index: -1;
      transition: opacity 0.5s linear;
      opacity: 0;
    }
    
    .gradient:hover::before {
      opacity: 1;
    }
    <div class="gradient"><a href="#">test to verify content remains visible & on top</a></div>
    Hover over the element above to fade the background gradient.
    
    <!-- Full write-up at http://keithjgrant.com/posts/2017/07/transitioning-gradients/ --

    【讨论】:

    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。
    • 对不起,我不知道。谢谢。
    【解决方案2】:

    如果你想要平滑的颜色变化,请添加 css transition

    document.addEventListener('click', function(event) {
      var xValue = Math.floor(Math.random() * 256);
      var yValue = Math.floor(Math.random() * 256);
      document.getElementById("bg").style.backgroundColor = 'rgb(' + yValue + ',' + yValue + ',' + xValue + ')';
    });
    * {
      padding: 0;
      margin: 0;
    }
    
    body {
      background-color: white;
      transition: 500ms background;
      height: 100vh;
      width: 100%;
    }
    <body id="bg">
      <div></div>
    </body>

    【讨论】:

      猜你喜欢
      • 2011-09-25
      • 1970-01-01
      • 2019-09-01
      • 2014-06-12
      • 1970-01-01
      • 2014-10-09
      • 2023-04-03
      • 2011-06-05
      • 2013-09-27
      相关资源
      最近更新 更多