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

后端 未结 4 1315
南旧
南旧 2021-02-04 06:40

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

4条回答
  •  再見小時候
    2021-02-04 07:19

    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

    and try something like this:

    $(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

提交回复
热议问题