开发者

How to keep track of a position no matter what screen size is?

I'm trying to make a widget that selects an area in the page using JavaScript but the issue is that when it saves the X/Y and Width/Height, it's actually only relevant to that screen size, so if we try to draw that selection on another user's computer, it'll go off the correct position.

On what to rely and how to keep track 开发者_StackOverflow社区of an x and y position no matter what the user's screen size is?


obj.offsetLeft and obj.offsetTop will always be relative to the top/left corner which is 0,0.

  • Center x = window.innerWidth / 2;
  • Center y = window.innerHeight / 2;
  • Object width = elementNode.offsetWidth;
  • Object height = elementNode.offsetHeight;

Position the object in the middle of the screen:

el = document.getElementById('my_div');
el.style.position = 'absolute';
el.style.left = Math.floor((window.innerWidth / 2) - (el.offsetWidth / 2)) + 'px';
el.style.top  = Math.floor((window.innerHeight / 2) - (el.offsetHeight / 2)) + 'px';

Working demo: http://jsfiddle.net/4aenr/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜