简体   繁体   中英

How to get parent div coordinates position on mouse click of child div

I am trying to create a minimap feature, I have two HTML elements and these can be image or div, so when a user clicks on an element it should give/translate the coordinates of another target element.

The clicked element size (w/h) will always be small and the position will be absolute. so far I am succeeded to get clicked element position but I am not able to translate these coordinates into the target element.

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

For example: 在此处输入图像描述

Map the coordinates using ratio of parent/child widths and heights

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM