javascript - onhover如何使用jquery获取图像的宽度和高度

标签 javascript jquery

我在网页中显示了 div 中的许多图像,div 和图像是通过循环动态创建的。

我需要使用 jquery 获取每个图像的宽度和高度,而不是像这样使用 id

 document.getElementById('Image/div id');

因为循环会根据条件动态创建很多图像 那么,当用户悬停/单击图像时,有什么方法可以获取图像的高度和宽度

我对此困扰了很长时间,最后希望我能得到解决方案

最佳答案

您可以使用 jQuery on() 将处理程序附加到最近的公共(public)父容器。这样,您至少可以控制希望此功能在哪些图像子集上生效。

$('#container').on('mouseover','img',function(){
    var width = $(this).width();
    var height = $(this).height();
});

喜欢:

<div>
    <img> //will not affect this one since it's not under "#container"
</div>
<div id="container">
   <img> //the handler affects this one
   <div>
      <img> //the handler also affects this one
   </div>
</div>

关于javascript - onhover如何使用jquery获取图像的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10207020/

相关文章:

javascript - 如何控制(音频缓冲区)AudioContext() 的音量?

javascript - 根据索引向 ngfor dom 添加元素

javascript - 无法将组件传递给组件

javascript - jquery 检查事件和 css 动画

javascript - 分割错误 : split is not a function

javascript - 400 或 500 级别的 Http 响应

javascript - 使用 JS 将网页元素保存为图像

javascript - jQuery 从左滑动 + 昏暗的背景

javascript - native 滚动延迟或停止 iOS 上的 JavaScript 执行

javascript - 试图通过隐藏字段获取后面代码中的时间偏移值。但我得到空字符串 ("")而不是偏移量