如何知道用户单击图像的左侧还是右侧?

时间:2018-12-14 19:02:47

标签: javascript jquery

我有一张图片:

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

我有一个画廊,我想知道用户是单击图像左侧以显示之前的图像还是单击右侧图像以显示下一个图像。

我尝试过:

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

});

但是它只是返回“左”,有什么想法如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您需要检查图像宽度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>

但是,请进一步阅读以了解大多数开发人员如何创建画廊。这就像在图像上放置一个叠加层(请参见橙色和绿色透明叠加层)一样简单。最后,删除颜色,没有人会看到他单击完全透明的元素...

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

答案 1 :(得分:1)

计算x位置,然后检查其是否小于图像宽度的一半。

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