我希望每次移动鼠标时我的背景图像都会改变。我将如何去做这件事。
问问题
539 次
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 回答