0

マウスを動かすたびに背景画像を変更したいと思います。どうすればこれを行うことができますか。

4

2 に答える 2

0
<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>
于 2015-02-27T02:00:53.230 に答える
0

mousemove イベントごとに背景画像を変更することはできません。画像の読み込みに十分な速度がありませんでした。

私は 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>
于 2015-02-27T02:48:20.213 に答える