javascript 如何在 jQuery 中使用 CSS 'background-image' 属性添加的图像上绑定单击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17582192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:52:20  来源:igfitidea点击:

How to bind click event on image added using CSS 'background-image' property in jQuery

javascriptjquerycss

提问by exexzian

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 clickevent on the image added using css's background-imageproperty.

我想我的问题通过标题本身就很清楚。尽管如此,我正在寻找一种click在使用 cssbackground-image属性添加的图像上绑定事件的方法。

I know, I could have achieved the similar functionality (of placing image over input fieldusing this wayor this way) by simply positioning <img>tag over inputbox 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.

我知道,我可以通过简单地将标签放置在框上然后处理所需的事件来实现类似的功能(使用这种方式这种方式将图像放置在输入字段上),但这种方式对于不同的输入字段似乎不太灵活宽度和高度,或者如果包装 div 没有作为它的属性。<img>inputposition:relative;

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

如果background-image无法在加载的图像上添加事件,那么如何使后面的方法更加灵活。

Hope I have conveyed my issues clearly.

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

Thanks.

谢谢。

采纳答案by Brian Hoover

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

链接到示例

回答by sandino

So you need to bind the click event to the image but not using an embebed attributte that's really a very good and dificult question by the way.

所以你需要将点击事件绑定到图像,但不使用嵌入属性,顺便说一下,这确实是一个非常好的和困难的问题。

I know my approach is complicated but is the only I can figure right now.

我知道我的方法很复杂,但这是我现在唯一能想到的。

You can get the image size (widthImage and heightImage) and know the position relatives of one to another (here is a way of calculating a position of an objet relative to anohter:jQuery get position of element relative to another element) you may use it to calculate the position of the input in the whole screen

您可以获得图像大小(widthImage 和 heightImage)并知道一个相对于另一个的位置相对关系(这是一种计算对象相对于另一个元素的位置的方法:jQuery get position of element relative to another element)您可以使用它计算输入在整个屏幕中的位置

and try something like this:

并尝试这样的事情:

$(document).ready(function(){

$(document).ready(function(){

  $('body').on('click', 'input.cross', function (e) {
        var widthInput = parseInt($(this).css('width'),10);
        var heightInput = parseInt($(this).css('height'),10);

        var position  = $(this).position();
        var top       = position.top;
        var left      = position.left;    

        var sizesRelativesInPercentage = $(this).css('background-size').split(/ +/);

        var widthPorcentage = parseInt(sizesRelativesInPercentage[0],10);
        var heightPorcentage =  parseInt(sizesRelativesInPercentage[1],10);

        var widthImage = (widthInput * widthPorcentage)/100;
        var heightImage = (heightInput * heightPorcentage)/100;

        var xFinalImageFinish= (left+widthInput);
        var yFinalImageFinish = (top+heightInput);


        // Fire the callback if the click was in the image
        if (e.pageX >= xFinalImageStart && e.pageX <= xFinalImageFinish &&
            e.pageY >= yFinalImageStart && e.pageY <= yFinalImageFinish) {

            // Prevent crazy animations and redundant handling
            $(this).off('click');
            alert('click on the image');

            //Do whatever you want
        }
    });
});

This is only an idea...I am trying to make a fiddle about this, hope so :O

这只是一个想法......我正在尝试解决这个问题,希望如此:O

回答by Xotic750

As pointed out by @Felix King

正如@Felix King 所指出的

Since the image is not an element in the document, it does not trigger events and you cannot bind a handler to it. You have to use a workaround.

由于图像不是文档中的元素,因此它不会触发事件并且您无法为其绑定处理程序。您必须使用一种解决方法。

Here is a possible work-around (in jquery, but could just as easily be POJS).

这是一个可能的解决方法(在 jquery 中,但也可以很容易地成为 POJS)。

CSS

CSS

.wrapper {
    padding: 1px;
    display: inline-block;
    border: 2px LightGray inset;
}
.wrapperFocus {
    border: 2px DarkGray inset;
}
.textInput {
    padding: 0;
    border:none;
    outline: none;
    height: 20px;
    width: 150px;
}
.cross {
    float: right;
    height: 20px;
    width: 20px;
    background-image:url('http://s20.postimg.org/6125okgwt/rough_Close.png');
    background-repeat:no-repeat;
    background-position: center;
    background-size:90%;
    cursor: pointer;
}

HTML

HTML

<fieldset class="wrapper">
    <input type="text" class="textInput" /><span class="cross"></span>
</fieldset>
<fieldset class="wrapper">
    <input type="text" class="textInput" /><span class="cross"></span>
</fieldset>
<fieldset class="wrapper">
    <input type="text" class="textInput" /><span class="cross"></span>
</fieldset>
<hr>
<button>submit</button>

Javascript

Javascript

$(document).on("click", "span.cross", function () {
    $(this).prev().val("");
}).on("focus", "input.textInput", function () {
    $(this).parent().addClass("wrapperFocus");
}).on("blur", "input.textInput", function () {
    $(this).parent().removeClass("wrapperFocus");
});

On jsfiddle

jsfiddle 上

Or if you want to do it without the additional CSS and HTML, then this should be cross-browser (POJS as you already have a jquery example).

或者,如果你想在没有额外的 CSS 和 HTML 的情况下做到这一点,那么这应该是跨浏览器的(POJS,因为你已经有了一个 jquery 示例)。

CSS

CSS

.cross {
    height: 20px;
    width: 150px;
    background-image:url('http://s20.postimg.org/6125okgwt/rough_Close.png');
    background-repeat:no-repeat;
    background-position:right center;
    background-size:10% 90%;
    z-index: -1;
    padding-right: 6%;
}

HTML

HTML

<input type="text" class="cross" />
<input type="text" class="cross" />
<input type="text" class="cross" />
<hr>
<button>submit</button>

Javascript

Javascript

function normalise(e) {
    e = e || window.event;
    e.target = e.target || e.srcElement;

    return e;
}

var getWidth = (function () {
    var func;

    if (document.defaultView.getComputedStyle) {
        func = document.defaultView.getComputedStyle;
    } else if (target.currentStyle) {
        func = function (t) {
            return t.currentStyle;
        }
    } else {
        func = function () {
            throw new Error("unable to get a computed width");
        }
    }

    return function (target) {
        return parseInt(func(target).width);
    };
}());

function isInputCross(target) {
    return target.tagName.toUpperCase() === "INPUT" && target.className.match(/(?:^|\s)cross(?!\S)/);
}

function isOverImage(e) {
    return (e.clientX - e.target.offsetLeft) > getWidth(e.target);
}

function clearCrossInput(e) {
    e = normalise(e);
    if (isInputCross(e.target) && isOverImage(e)) {
        e.target.value = "";
    }
}

document.body.onclick = (function () {
    var prevFunc = document.body.onclick;

    if ({}.toString.call(prevFunc) === "[object Function]") {
        return function (ev) {
            prevFunc(ev);
            clearCrossInput(ev);
        };
    }

    return clearCrossInput;
}());

On jsfiddle

jsfiddle 上

But if you want the cursor to change when hovered over the position then you will need to do some extra work. Like this (you could just as easily do this with jquery too).

但是,如果您希望光标悬停在该位置上时发生变化,那么您将需要做一些额外的工作。像这样(你也可以用 jquery 轻松地做到这一点)。

Javascript

Javascript

function hoverCrossInput(e) {
    e = normalise(e);
    if (isInputCross(e.target)) {
        if (isOverImage(e)) {
            e.target.style.cursor = "pointer";
            return;
        }
    }

    e.target.style.cursor = "";
}

document.body.onmousemove = (function () {
    var prevFunc = document.body.onmousemove;

    if ({}.toString.call(prevFunc) === "[object Function]") {
        return function (ev) {
            prevFunc(ev);
            hoverCrossInput(ev);
        };
    }

    return hoverCrossInput;
}());

On jsfiddle

jsfiddle 上

回答by Stephen P

I do something similar by using an <input type="text" ... >immediately followed by an <input type="button">

我通过使用<input type="text" ... >紧跟一个<input type="button">

The button is given a background image and positioned-relative to move it into the text field; essentially...

按钮被赋予一个背景图像并相对定位以将其移动到文本字段中;本质上...

position: relative;
top: 4px;
right: 1.6em;
height: 16px;
width: 16px;
border: none;

Then I just add a dead-plain click handler to the button, no computations necessary.

然后我只向按钮添加一个简单的点击处理程序,不需要计算。

The height x width would depend on your image, and you would tweak the top and right to fit your situation.

高度 x 宽度取决于您的图像,您可以调整顶部和右侧以适应您的情况。

This fiddleshows it pared down to the bare essentials.

这个小提琴显示它缩减到最基本的要素。