简体   繁体   English

采取最高和最低的位置,并在javascript中转换为百分比

[英]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. 我有一个正方形区域,可捕获鼠标单击并在该位置当前添加一个新的div。 My aim is to take those top: Ypx; 我的目标是超越那些:Ypx; left: Xpx; 左:Xpx; coordinates and turn them into percentages using javascript as the square region will be set to different sizes on different pages. 坐标,并使用javascript将其转换为百分比,因为方形区域将在不同页面上设置为不同大小。

My current example http://jsfiddle.net/p5h26/1/ 我当前的示例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. 当您用小提琴演奏很多次单击时,附加的div开始碰撞并破坏彼此的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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