我在这里遗漏了一些东西:
<!-- 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/