简体   繁体   English

“onmouseout”不起作用。 图像没有改变

[英]“onmouseout” isn't working. The image doesn't change

I want an image to change when it is hovered on.我希望图像在悬停时发生变化。 So far my code is fine.到目前为止,我的代码很好。 But I want the image to change back to its original image when mouse leaves the image.但是我希望当鼠标离开图像时图像变回原来的图像。 This is where my code doesn't work properly.这是我的代码无法正常工作的地方。 What is the problem and how can I fix it?有什么问题,我该如何解决? I really appreciate your help.我真的很感谢你的帮助。

This is my html code:这是我的 html 代码:

<div onmouseover="show_large(this);" onmouseout="show_normal(this);">
  <img src="2.JPG">
</div>
<script>
function show_large(element){
  element.innerHTML=
  '<img src="1.JPG">';
}
function show_normal(element){
  element.innerHTML=
  '<img src="2.JPG">';
}
</script>

And this is my css code:这是我的 css 代码:

div{
  width: 25%;
  margin: 0;
}
img{
  width: 100%;
  margin: 0;
}

You can achive this only with CSS and HTML, just add background-image property on your div and change img on :hover , like so:您只能使用 CSS 和 HTML 来实现此目的,只需在 div 上添加background-image属性并在:hover上更改 img ,如下所示:

div{
background-image: url('first-img-src.png');
transition: background-image 1s ease-in-out;
}
div:hover{
background-image: url('second-img-src.png');
}

EDIT: You can achive same thing using mouseenter and mouseleave with changeing img.src property:编辑:您可以通过img.src属性使用mouseentermouseleave来实现相同的目标:

const img = document.querySelector('img');
img.addEventListener('mouseenter', (e) => {
  img.src = 'second.png'
})
img.addEventListener('mouseleave', (e) => {
  img.src = 'first.png'
})

Since images will have default hover events, you need to disable them for it to work on the parent div.由于图像将具有默认的 hover 事件,因此您需要禁用它们才能在父 div 上工作。 You can disable them by adding pointer-events: none to img tag您可以通过添加pointer-events: noneimg标签来禁用它们

 function show_large(element) { element.innerHTML = '<img src="https://randomuser.me/api/portraits/men/51.jpg">'; } function show_normal(element) { element.innerHTML = '<img src="https://randomuser.me/api/portraits/men/50.jpg">'; }
 div { width: 25%; margin: 0; } img { width: 100%; margin: 0; pointer-events: none; }
 <div onmouseover="show_large(this);" onmouseout="show_normal(this);"> <img src="https://randomuser.me/api/portraits/men/50.jpg"> </div>

You can simply do it using css it self.您可以简单地使用 css 它自己来完成。 working jsFiddle工作的jsFiddle

 .image-container{ width: 300px; }.over{ display: none; }.image-container:hover.main{ display: none; }.image-container:hover.over{ display: block; }
 <div class="image-container"> <img class="main" src="https://www.rd.com/wp-content/uploads/2019/04/shutterstock_1013848126.jpg" width="100%" /> <img class="over" src="https://www.rd.com/wp-content/uploads/2019/05/shutterstock_671541538-e1557714950453.jpg" width="100%" /> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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