如何在jQuery中使用CSS'background-image'属性在图像上添加点击事件 [英] How to bind click event on image added using CSS 'background-image' property in jQuery

查看:1063
本文介绍了如何在jQuery中使用CSS'background-image'属性在图像上添加点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的小提琴链接



我想我的问题是清楚的标题本身。仍然,我正在寻找的是一种方法绑定 c $ 背景图像属性添加的图像单击



我知道,我可以使用 jsfiddle.net/vnodkumar1987/nxKRX/3/rel =noreferrer>这种方式通过简单地将< img> 标记放置在输入框中,然后处理所需的事件但是这种方式对于不同宽度和高度的输入字段似乎不太灵活,或者如果包装div没有 position:relative; 作为其属性。



如果在加载了 background-image 的图像上添加事件是不可能的,那么如何使后面的方法更加灵活。 p>

希望我已清楚地表达了我的问题。



谢谢。

解决方案

这样的东西似乎也有效:

  ').click(function(e){
var mousePosInElement = e.pageX - $(this).position()。left;
if(mousePosInElement> $(this).width()){
$(this).val('');
}
});

链接到示例


Here is my fiddle link

I guess my question is clear by title itself. Still, what I am looking for is an way to bind click event on the image added using css's background-image property.

I know, I could have achieved the similar functionality (of placing image over input field using this way or this way) by simply positioning <img> tag over input box and then handling the required events but that way didn't seem too flexible with input fields of varying width and height or if the wrapping div doesn't have position:relative; as its property.

If adding event on image loaded with background-image is not possible then how to make the later approach more flexible.

Hope I have conveyed my issues clearly.

Thanks.

解决方案

Something like this appears to also work:

$('.cross').click(function(e) {
  var mousePosInElement = e.pageX - $(this).position().left;
  if (mousePosInElement > $(this).width()) {
     $(this).val(''); 
  }
});

Link to example

这篇关于如何在jQuery中使用CSS'background-image'属性在图像上添加点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆