[英]how do I get my background image to change every time the mouse moves using the onmousemove function?
I would like my background image to change every time the mouse is moved. 我希望每次移动鼠标时都会更改背景图像。 How would I go about doing this .
我该怎么做呢
<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>
You can not change the background image as each mousemove event. 您不能将每个mousemove事件更改为背景图像。 The image could not be loaded fast enough.
图像无法足够快地加载。
I used css3 animations (with -webkit prefix only, adapt to your browser if needed). 我使用了css3动画(仅使用-webkit前缀,如果需要,可以适应您的浏览器)。 Animation is triggered only if the mouse is moving.
仅在鼠标移动时才会触发动画。 See code below and this demo
请参阅下面的代码和此演示
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.