简体   繁体   中英

Take top and left positions and convert to percent in javascript

I have a square region that captures the mouse clicks and adds a new div in that spot currently. My aim is to take those top: Ypx; left: Xpx; coordinates and turn them into percentages using javascript as the square region will be set to different sizes on different pages.

My current example http://jsfiddle.net/p5h26/1/

//current js for the effect( some small diferences in the click event using backbone events)
$(".div_container").click(function(e, ui){
          var parentOffset = $(this).offset();         
          var relativeXPosition = (e.pageX - parentOffset.left);
          var relativeYPosition = (e.pageY - parentOffset.top);         
          $(".div_container").append('<div class="MAPICON" style="top:'+relativeYPosition+'px; left:'+relativeXPosition+'px;"></div>');
});

Edit: I wish to be able to take the top and left positions and save them into my database as a percent, I do not know how to do the math for that or where i would start.

You can calculate the percentages with code like this:

var $this = $(this), offset = $this.offset(),
    width = $this.innerWidth(), height = $this.innerHeight();
var parentOffset = $(this).offset();         
var relativeXPosition = (e.pageX - parentOffset.left),
    percentx = relativeXPosition/width;
var relativeYPosition = (e.pageY - parentOffset.top),
    percenty = relativeYPosition/height;

But I think you do want to change from relative to absolute positioning. When playing with your fiddle for very many clicks, the appended divs start to collide and disrupt each others' positions.

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