所以基本上我想通过鼠标在按钮上传递来改变图像。使用当前的代码,我可以在单击按钮时更改图像,但是当我将鼠标放在按钮上而无需单击按钮时,我也需要更改图像。什么好主意吗?
<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" />
和javascript:
var image = document.getElementById('firstimage');
function changeImage(uri) {
image.src = uri;
}
你的意思是这样吗?
和onclick
一样,你可以使用onmouseover
,它和css
:hover
是一样的
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" />
你可以试试这个,只是给你的按钮一个Id,以便之后得到它。
var button = document.getElementById("buttonId")
var image = document.getElementById('firstimage')
button.onmouseover = function(uri){
image.src = uri
}