简体   繁体   中英

How can I change image source in a div on mouse move with jquery?

I'm trying to teach myself how to code (especially websites). I have a good knowledge of html and css and I'm currently learning js. But know I need the help of the community to make progress!

I am wondering how to achieve this effect of changing image source multiple times (in order) on every mouse move? exemple: http://next2nothi.ng/

After few searches I am not able to find the good solution to achieve that…

Thanks in advance for your help!

Try

 let list=[...Array(20)].map((x,i)=>`https://picsum.photos/150/150?image=${i}`); let index=0; document.addEventListener("mousemove", function(){ document.getElementById("myImg").src = list[ ++index % list.length]; }); 
 <img id="myImg" width="150px" heigh="150px" > 

Here is a simple example. So you need to have a list of images that you want to display when the mouse move event is fired on a specific div, you can pick a random image from the list and set it as background image of the div:

function SwapBackgroundImage(){
   var listOfImages = ['urlToimage1','urlToImage2', 'and etc'];    // so have your array
    $('#myDiv').on('mousemove',function(){
          // i am picking the first image here, but you can google how to pick a random element in an array and use that
         $(this).css('background-image', 'url(' + listOfImages[0]+ ')');
    });

}

<div id="myDiv"></div>

Thats it.

Hello Ted_M you no need to use jQuery with it, it is very simple and you can receive this by few lines of code, ie declare a function which will be check if the mouse has moved or not.

var myListener = function () {
document.removeEventListener('mousemove', myListener, false);
// do stuff
document.getElementById("imageid").src="../template/save.png";
};
document.addEventListener('mousemove', myListener, false);

Now you need to change the image url by

document.getElementById("imageid").src="../template/save.png";

So now the method will be

var myListener = function () {
document.removeEventListener('mousemove', myListener, false);
// do stuff
  document.getElementById("imageid").src="../template/save.png";
};
document.addEventListener('mousemove', myListener, false);

Thats it, you have to store the imageURL in an array if you want to do same as the link you provide. Thank you Comment down for any help.

let listImageURL = ['urlToImg1.png','urlToImg2.png','..3.png', ... till how much you need];
let body = document.querySelector('body').addEventListener('mouseover',function(event){
     // take list of images
      for(let i = 0; i<=listImageURL.length-1;i++){
           event.target.style.background = `url(${listImageURL[i]})`;
       }
});

HTML:
<body>
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM