如何使用onmousemove函数在每次鼠标移动时更改背景图像

how do I get my background image to change every time the mouse moves using the onmousemove function?

本文关键字:移动 图像 背景 鼠标 onmousemove 何使用 函数      更新时间:2024-06-21

我希望每次移动鼠标时都能更改背景图像。我该怎么做呢。

<img id="background" src="" onmouseover="next()">
<script>
var picNum = 3;
//number of pictures you have
var picSrc = ["pic1Src", "pic2Src", "pic3Src"];
//provide url for each picture or directory for each
var currentPic = 1;
//initialize var for pic number
next(){
var obj = document.getElementById('background');
//Set obj to background
obj.src = picSrc[currentPic];
//Set obj's source to currentPic
var currentPic = currentPic + 1 % picNum
//Increases currentPic by one for next time, however if it goes over the         number of pics you have, it goes back to zero.
}
</script>

您不能将背景图像更改为每个鼠标移动事件。图像加载速度不够快。

我使用了css3动画(仅带有-webkit前缀,如果需要,请根据您的浏览器进行调整)。只有当鼠标移动时才会触发动画。请参阅下面的代码和此演示

<html>
  <head>
      <style>
          body{
           background:linear-gradient(90deg, #FF4E50 10%, #F9D423 90%); 
          }
          body.mouseMove{
            -webkit-animation-duration: 6s;
            -webkit-animation-iteration-count: infinite;
            -webkit-animation-name: bg-change;
          }
          @-webkit-keyframes bg-change {
            0% {background:linear-gradient(90deg, #24C6DC 10%, #514A9D 90%); }
            30% { background:linear-gradient(90deg, #FF4E50 10%, #F9D423 90%);}
            60% {background:linear-gradient(90deg, #B3FFAB 10%, #12FFF7 90%);}
            100% {background:linear-gradient(90deg, #24C6DC 10%, #514A9D 90%); }
          }
      </style>
    </head>
  <body>
      <script type="text/javascript">
          var body= document.querySelector("body");
          var endMoveTimeout;
          body.addEventListener('mousemove',function(){
            clearTimeout(endMoveTimeout);
            body.classList.add("mouseMove");
            endMoveTimeout= setTimeout(function(){
              body.classList.remove("mouseMove");
            },1000);
          });

          body.addEventListener('animationiteration',function(e){
            console.log(e);
          });
      </script>
  </body>
</html>