我在这里缺少一些东西:
<!-- 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
第一次将鼠标悬停在图像上没有返回任何内容,因为您没有在style标签中定义宽度(第二次起作用是因为在鼠标移开时您正在使用函数)。您需要做的就是将宽度移动到CSS中,而不使用Xio8Hogh
属性。
有两个建议:首先,以一种可以解释功能将要执行的功能的方式命名您的功能,而不仅仅是胡言乱语。这将使您更容易调试,并且如果您在团队中工作,也将使团队成员更容易理解您的代码在做什么。另外,请尝试在样式表中定义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/