admin管理员组

文章数量:1313795

I have a div with background 30% resized and a img sized 100%

I would like detect onclick only on the background resized div (purple in the picture below), not on all element

What is the best way?

Thank you in advance.

<div class="div1" style="width:600px; background:url(img/litlePict.png) no-repeat scroll center center / 30% auto">
    <img class="store" src="img/mypict.png" width="100%" />
</div>

UPDATE

This is what i would like do!

I have a div with background 30% resized and a img sized 100%

I would like detect onclick only on the background resized div (purple in the picture below), not on all element

What is the best way?

Thank you in advance.

<div class="div1" style="width:600px; background:url(img/litlePict.png) no-repeat scroll center center / 30% auto">
    <img class="store" src="img/mypict.png" width="100%" />
</div>

UPDATE

This is what i would like do!

Share Improve this question edited Nov 10, 2015 at 16:52 P. Frank asked Nov 10, 2015 at 15:31 P. FrankP. Frank 5,7456 gold badges24 silver badges52 bronze badges 7
  • I think the best way is to add a div in the .div1 – Hobroker Commented Nov 10, 2015 at 15:40
  • I don't think you'll be able to do that. Why not set your background image to 100% and your img to 30%? You would be able to catch a click on it alot easier. Otherwise you could create a blank div that's positioned on top of the image that matches the size of the background image and have a click listener on it. – Darren Gourley Commented Nov 10, 2015 at 15:40
  • 1 It's unclear to me how the background is visible behind the image. Is the latter transparent? – hindmost Commented Nov 10, 2015 at 15:42
  • How is the background image getting in front of the image inside of it? – Bill Criswell Commented Nov 10, 2015 at 15:43
  • yes, i have a img with transparence. @DarrenGourley I use that because with animate the img not follow the div – P. Frank Commented Nov 10, 2015 at 15:44
 |  Show 2 more ments

7 Answers 7

Reset to default 2

I didn't test this code, but it might give you a hint on how to achieve something like this!

$('.element').on('click', function (e) {
    var xPossition = $(this).position().left; // The distance between 'zero' and the left of the element on the X Axis
    var yPossition = $(this).position().top;  // The distance between 'zero' and the top of the element on the Y Axis
    var elemWidth  = $(this).width(); // The height of the element
    var elemHeight = $(this).height(); // The widthof the element

    var mouseX = e.pageX - xPossition; // The possition of the mouse on the X Axis of the screen removing the distance to the LEFT of the element clicked
    var mouseY = e.pageY - yPossition; // The possition of the mouse on the Y Axis of the screen removing the distance to the TOP of the element clicked

    // Check if the position of the mouse relative to the element is between the first 35% and the last 35% of the width and height of the element
    if ( (mouseX > elemWidth*0.35 && mouseX < elemWidth - elemWidth*0.35) && (mouseY > elemHeight*0.35 && mouseY < elemHeight - elemHeight*0.35) ) {
        // Do stuff
    }
});

I don't think it is possible to do so with so few HTML tags. You should rather get another div in the div1, and then play with z-index and event propagation.

You could do this putationally, getting the background-size dynamically and then applying it to the div. The contents of the div don't really matter in this case, so I left out the image.

// Get all the elements and apply the following code using an array forEach
Array.prototype.slice.call(document.querySelectorAll('.bg-click')).forEach(function(a){
  var bgsize = parseInt(a.style.backgroundSize, 10) / 100;
  a.addEventListener('click', function(e){
    // Get the current width and height (expected value in pixels)
    var w = parseInt(a.style.width, 10);
    var h = parseInt(a.style.height, 10);
    // If the x click is outside of the center, or the y click is
    // use preventDefault to stop the click.
    if(
      e.layerX < w / 2 - w * (bgsize / 2) 
      || e.layerX > w / 2 + w * (bgsize / 2)
      || e.layerY < h / 2 - h * (bgsize / 2) 
      || e.layerY > h / 2 + h * (bgsize / 2)
    ){
      e.preventDefault();
    } else {
    // Otherwise, execute this
      console.log('clicked in center');
      alert('clicked in center');
    }
  })
});
<div class="bg-click" style="background: url(http://placehold.it/200x200) 50% 50% no-repeat; width: 200px; height: 200px; background-size: 30% 30%;"></div>

Since you background isn't actually an element, you have to do the putation yourself, so why not try it with an actual element:

Array.prototype.slice.call(document.querySelectorAll('.bg')).forEach(function(a){
  a.addEventListener('click', function(){
    console.log('clicked');
    alert('clicked');
  })
})
.bg-holder {
  width: 200px;
  height: 200px;
  position: relative;
}
.bg-holder .bg {
  position: absolute;
  left: 50%;
  top: 50%%;
  width: 30%;
  height: 30%;
  -webkit-transform: translate(-50%,-50%);
  transform: translate(-50%,-50%);
  background: url(http://placehold.it/200x200);
}
<div class="bg-holder">
  <div class="bg"></div>
</div>

Put another div within the div1. Size and position this inner div in the place you want.

It will be transparent so the appearance won't be bothered. You can use 'onClick' on this div instead.

You could check if the underlying div is present in position you clicked on,

try this:

var div = document.querySelector('div');

div.addEventListener('click',function(e){
     // on top layer
     e.target.style.pointerEvents = "none";

     var under = document.elementFromPoint(e.clientX, e.clientY);
    
     if (under === div)
      under.style.background='blue';
   
      //restore pointer-events
      e.target.style.pointerEvents = "visiblePainted";

   });
div{
    width:200px;
    height:200px;
    background:red;
    position:absolute;
    left:50%;
    top:50%;
    transform:translate(-50%,-50%);
}
img{
    width:600px;
    height:600px;
    position:relative;
    left:50%;
    top:50%;
    transform:translate(-50%,-50%);
    background:rgba(0,225,0,0.3)
}
<div>
    <img class="store" src="img/mypict.png" width="100%" />
</div>

in this scenario you entire background div will be resized not background-image like in your example.

Ok, revising my answer after reading your update.

<html>
    <head>      
        <script src="https://code.jquery./jquery-2.1.4.min.js"></script>
    </head>

    <body>
        <div id="con" style="position:relative; width:60px; height:60px; background-color: #ff0000;">
            <div id="smallerDiv" style="position:absolute; top:20px; left:20px;  width:20px; height:20px; background-color: #ededed;">              
            </div>
            <img id="theImg" src="imgs/topImg.png" style="opacity:0; position:absolute; top:0px; left:0px; pointer-events:none;"/>
        </div>
    </body>

    <script>

        $("#con").animate({"width":"600px","height":"600px"}, 1000);
        $("#smallerDiv").animate({"width":"200px","height":"200px","top":"200px",'left':"200px"}, 1000);

        document.getElementById("smallerDiv").onclick = function(){
            $("#theImg").animate({"opacity":1}, 500);
        };

    </script>
</html>

This will do exactly what you need.

document.getElementsByTagName('img')[0].onclick(
   function(e){ 
       e.stopImmediatePropogation(); 
       // do other stuff
   });

本文标签: javascriptDetect click on div background 30 resizedStack Overflow