Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

javascript - how can I change an image by hovering a button? More details below

So basically I want to change an image by passing over the mouse on a button. with the current code I am able to change the image when the button is clicked, but I also need it to change when I put the mouse over the button without having to click it. Any ideas?

<body>
<input type="button" class = "button" onclick="changeImage('https://www.gettyimages.es/gi-resources/images/500px/983794168.jpg')" value="button1" />


<img src="https://images.unsplash.com/photo-1503023345310-bd7c1de61c7d?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW58ZW58MHx8MHw%3D&ixlib=rb-1.2.1&w=1000&q=80" class = "img" id="firstimage" width="310">



<input type="button" class = "button4" onclick="changeImage('https://images.unsplash.com/photo-1494548162494-384bba4ab999?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MXx8c3VucmlzZXxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&w=1000&q=80')" value="button2" />

and the javascript:

var image = document.getElementById('firstimage');

function changeImage(uri) {
  image.src = uri;
}
question from:https://stackoverflow.com/questions/66066164/how-can-i-change-an-image-by-hovering-a-button-more-details-below

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Do you mean like this?
like onclick, you can use onmouseover which is same as :hover in css

var image = document.getElementById('firstimage');

function changeImage(uri) {
  image.src = uri;
}
<input type="button" class = "button" onclick="changeImage('https://www.gettyimages.es/gi-resources/images/500px/983794168.jpg')"

onmouseover="changeImage('https://www.gettyimages.es/gi-resources/images/500px/983794168.jpg')" 

value="button1" />


<img src="https://images.unsplash.com/photo-1503023345310-bd7c1de61c7d?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW58ZW58MHx8MHw%3D&ixlib=rb-1.2.1&w=1000&q=80" class = "img" id="firstimage" width="310">



<input type="button" class = "button4" onclick="changeImage('https://images.unsplash.com/photo-1494548162494-384bba4ab999?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MXx8c3VucmlzZXxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&w=1000&q=80')"

onmouseover="changeImage('https://images.unsplash.com/photo-1494548162494-384bba4ab999?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MXx8c3VucmlzZXxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&w=1000&q=80')"  value="button2" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...