How to know if user clicks in the left of an image or in the right? [duplicate]

时间秒杀一切 提交于 2021-01-29 08:31:02

问题


I have an image:

<img src="https://upload.wikimedia.org/wikipedia/commons/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg" class=imgclick>

I have a gallery and I'd like to know if user click on the left of the image to show the image before or if he clicks on the right to show next one.

I tried:

$('.imgclick').click(function (e){

    var elm = $(this);
    var xPos = e.pageX - elm.offset().left;

    var total = e.pageX;

    if((total / 2) <= xPos){
        alert("left");
    }
    else{
        alert("right");
    }

});

but it is only returning "left", any ideas how to solve this?


回答1:


Calculate the x position and then check if its less than half of width of image.

$(".imgclick").on("click", function(event) {
    var x = event.pageX - this.offsetLeft;
    alert(x < this.width / 2 ? 'Left' : 'Right');
}); 



回答2:


You need to check from half the size of the image width elm.width()

$('.imgclick').click(function (e){

    var elm = $(this);
    var xPos = e.pageX - elm.offset().left;

    if((elm.width() / 2) >= xPos){
        alert("left");
    } else {
        alert("right");
    }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://upload.wikimedia.org/wikipedia/commons/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg" class=imgclick>

But, read further to see how most developers create a gallery. It's as simple as putting an overlay (see orange and green transparent overlay), over the image(s). At the end, you remove the colors and no one will see that he clicks on a completely transparent element...

$('.gallery [data-gallery-control]').on('click', function(){
  alert($(this).data('gallery-control'));
  // move on from here if "right" or if "left"
  // do what ever you need
});
.gallery {
  position: relative;
  border: solid 2px red;
}

.gallery img {
  object-fit: cover;
  width: 100%;
}

.gallery [data-gallery-control] {
  position: absolute;
  text-indent: -10000px;
  display: block;
  top: 0;
  width: 50%;
  height: 100%;
  background-color: orange;
  opacity: 0.5;

}

.gallery [data-gallery-control="right"] {
  right: 0;
}

.gallery [data-gallery-control="left"] {
  left: 0;
  background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="gallery">
<img src="https://upload.wikimedia.org/wikipedia/commons/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg" class=imgclick>
<a data-gallery-control="right" href="#path-to-next-image">right</a>
<a data-gallery-control="left" href="#path-to-prev-image">left</a>
</div>


来源:https://stackoverflow.com/questions/53785504/how-to-know-if-user-clicks-in-the-left-of-an-image-or-in-the-right

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!