繁体   English   中英

如何在jQuery中使用CSS'background-image'属性绑定图像上的click事件

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

这是我的小提琴链接

我想我的问题很清楚标题本身。 不过,我正在寻找的是一种在使用css的background-image属性添加的图像上绑定click事件的方法。

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

如果无法在加载了background-image上添加事件,那么如何使后一种方法更加灵活。

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

谢谢。

这样的东西似乎也有效:

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

链接到示例

因此,您需要将click事件绑定到图像,但不要使用嵌入式attributte,顺便提一下这是一个非常好的和困难的问题。

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

你可以得到图像大小(widthImage和heightImage)并知道彼此的位置亲属(这里是一种计算objet相对于anohter的位置的方法: jQuery获取元素相对于另一个元素的位置 )你可以使用它计算整个屏幕中输入的位置

并尝试这样的事情:

$(文件)。就绪(函数(){

  $('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
        }
    });
});

这只是一个想法......我试图弄清楚这一点,希望如此:哦

正如@Felix King指出的那样

由于图像不是文档中的元素,因此它不会触发事件,也不能将处理程序绑定到它。 您必须使用变通方法。

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

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

<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

$(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");
});

jsfiddle

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

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

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

使用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;
}());

jsfiddle

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

使用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;
}());

jsfiddle

我通过使用<input type="text" ... >然后紧跟<input type="button">来做类似的事情

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

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

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

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

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

暂无
暂无

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

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