javascript - 鼠标悬停时调整图像大小

标签 javascript

我在这里遗漏了一些东西:

<!-- 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>

问题是我需要将鼠标悬停在图像上两次才能获得正确调整大小的 onmouseover 图像(第一个 onmouseover 大概是为了获取图像尺寸)。我错过了什么?

这是一个 JS Bin:https://jsbin.com/tesesi/edit?html,output

最佳答案

问题是,当您第一次将鼠标悬停在图像上时,x.style.width 不会返回任何内容,因为您没有在样式标记中定义宽度(它第二次起作用,因为在mouseout 您正在使用 Xio8Hogh 函数在 CSS 中定义宽度)。您所需要做的就是将宽度移至 CSS 中,而不是使用 width 属性。

一些建议:首先,以能够解释该函数将做什么的方式命名您的函数,而不仅仅是胡言乱语。这将使您更容易调试,并且如果您在团队中工作,则将使您的团队成员更容易理解您的代码在做什么。另外,尝试在样式表中定义 CSS,而不是在 HTML 中内联。这将使您的代码更清晰。

<!-- 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>

除此之外,我还想提一下,此功能可以完全在 CSS 中完成,而不需要 JavaScript,如下所示:

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>

关于javascript - 鼠标悬停时调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55814904/

相关文章:

javascript - 如何在nestjs中转换api响应?

javascript - Vuejs 提交突变失败

javascript - 如何在同一aspx页面的新窗口中显示最大化的gridview?

javascript - 删除所有 CSS 规则

javascript - 同步 promise 解析(bluebird vs. jQuery)

javascript - 如何查找xml节点中属性的具体位置

javascript - Chrome 开发者工具自更新 32.0.1700.76 m 后无响应

javascript - 将 HTML 表单的输入转换为 Javascript?

javascript - 将数据从其他网站内联 CSS 粘贴到 CK 编辑器中,在 Google Chrome 中丢失,但在 IE 和 Firefox 中不丢失

javascript - 如何在 css 类的 onclick 事件上调用函数