简体   繁体   English

如何正确使用addEventListener图像?

[英]How to use addEventListener for image properly?

I like to measure the width of an image, which was loaded by user click. 我喜欢测量图像的宽度,该图像是通过用户单击加载的。 I need the width to adjust the position button next to the image. 我需要宽度来调整图像旁边的位置按钮。 Is this possible to do in Javascript? 使用Javascript可以做到吗?

here is my code: 这是我的代码:

document.getElementById('preIMG').addEventListener("load", posButton2IMG); 


function posButton2IMG(){
   var imgWidth = document.getElementById('preIMG').clientWidth;
   var imgWidPos = document.getElementById('picture_preview').clientWidth - imgWidth + 15;
   document.getElementById('gear_butto').style.right = (imgWidPos*0.5) + "px";
}  

edit: In fact the user can explore several images and addEventListener seems only working for the first time the side is load. 编辑:实际上,用户可以浏览多个图像,并且addEventListener似乎仅在第一次加载侧面时起作用。

不要在click事件中调用函数,只需传递函数JavaScript将在触发click事件时调用您的函数

document.getElementById('preIMG').addEventListener("load", posButton2IMG); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM