jquery 如何在鼠标单击子div时获取父div坐标位置

bfrts1fy  于 2023-01-08  发布在  jQuery
关注(0)|答案(1)|浏览(229)

我正在尝试创建一个小Map功能,我有两个HTML元素,它们可以是图像或div,所以当用户单击一个元素时,它应该给予/转换另一个目标元素的坐标。
点击的元素大小(宽/高)将始终很小,位置将是绝对的。到目前为止,我成功地获得了点击的元素位置,但我无法将这些坐标转换为目标元素。
https://jsfiddle.net/shoaib_ijaz/n1hzuc9r/

$(".child").click(function(e) {

   var offset = $(this).offset();

   var left = e.pageX - offset.left;
   var top = e.pageY - offset.top;

   var circle = $("<div />", {
     class: 'circle'
   });

   $(circle).css({
     left: left,
     top: top
   });

   $(".parent").append(circle);
 });
.parent {
  border: 3px solid #000;
  background: #898383;
  width: 100%;
  height: 300px;
}

.child {
  background: #fff;
  position: absolute;
  right: 15px;
  bottom: 40px;
  width: 200px;
  height: 100px;
  border: 2px solid #eff431;
}

.circle {
  width: 10px;
  height: 10px;
  background: red;
  -moz-border-radius: 50px;
  -webkit-border-radius: 50px;
  border-radius: 50px;
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

 <div class="parent">
   <div class="child">
     child
   </div>
 </div>

 <!-- some times the child element can be outside the parent element -->

例如:

2vuwiymt

2vuwiymt1#

使用父级/子级宽度和高度的比率Map坐标

$(".child").click(function(e) {

   var offset = $(this).offset();

   var ratioX = $(".parent").width() / $(this).width();
   var ratioY = $(".parent").height() / $(this).height();

   var left = (e.pageX - offset.left) * ratioX;
   var top = (e.pageY - offset.top) * ratioY;

   var circle = $("<div />", {
     class: 'circle'
   });

   $(circle).css({
     left: left,
     top: top
   });

   $(".parent").append(circle);
 });
.parent {
  border: 3px solid #000;
  background: #898383;
  width: 100%;
  height: 300px;
}

.child {
  background: #fff;
  position: absolute;
  right: 15px;
  bottom: 40px;
  width: 200px;
  height: 100px;
  border: 2px solid #eff431;
}

.circle {
  width: 10px;
  height: 10px;
  background: red;
  -moz-border-radius: 50px;
  -webkit-border-radius: 50px;
  border-radius: 50px;
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

 <div class="parent">
   <div class="child">
     child
   </div>
 </div>

 <!-- some times the child element can be outside the parent element -->

相关问题