简体   繁体   中英

Image resize on mouseover

I am missing something here:

<!-- image is 1920 × 1080 pixels (W x H) -->
<a href="https://persagen.com/files/misc/postgres-x_on-pset_align_wrapped.png/"><img alt="postgres-x_on-pset_align_wrapped.png/" onmouseover="iyu3Pheu(this)" onmouseout="Xio8Hogh(this)" border="0" src="https://persagen.com/files/misc/postgres-x_on-pset_align_wrapped.png" width="300" style="padding-left:1px;"></a>
<script>
  function iyu3Pheu(x) {
    if(x.style.width < 500){
      x.style.width = "50%";
    }
    else {
      x.style.width = "100%";
    }
  }
  function Xio8Hogh(x) {
    x.style.width = "300px";
  }
</script>

The issue is I need to mouseover the image twice to get the properly resized onmouseover image (the first onmouseover , presumably, to get the image dimensions). What am I missing?

Here is a JS Bin: https://jsbin.com/tesesi/edit?html,output

The issue is that x.style.width is returning nothing the first time you mouse over the image since you're not defining the width in the style tag(it works the second time because on mouseout you are defining the width in CSS using the Xio8Hogh function). All you need to do is move the width into the CSS instead of using the width attribute.

A couple of suggestions: Firstly, name your functions in a way that they explain what the function will do rather than just gibberish. This will make it easier for you to debug and if you are working in a team, it will make it easier for your team members to understand what your code is doing. Also, try defining your CSS in a stylesheet rather than inline in the HTML. This will make your code cleaner.

 <!-- image is 1920 × 1080 pixels (W x H) --> <a href="https://persagen.com/files/misc/postgres-x_on-pset_align_wrapped.png/"><img alt="postgres-x_on-pset_align_wrapped.png/" onmouseover="iyu3Pheu(this)" onmouseout="Xio8Hogh(this)" border="0" src="https://persagen.com/files/misc/postgres-x_on-pset_align_wrapped.png" style="width:300px;padding-left:1px;"></a> <script> function iyu3Pheu(x) { if(x.style.width < 500){ x.style.width = "50%"; } else { x.style.width = "100%"; } } function Xio8Hogh(x) { x.style.width = "300px"; } </script> 

With that out of the way, I also wanted to mention that this functionality can be done entirely in CSS without any need for JavaScript like so:

 img { width:300px; } a:hover img { width:100% } 
 <a href="https://persagen.com/files/misc/postgres-x_on-pset_align_wrapped.png/"><img alt="My Image" border="0" src="https://persagen.com/files/misc/postgres-x_on-pset_align_wrapped.png"></a> 

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