如何获取元素相对于窗口的当前位置

时间:2016-12-26 11:33:34

标签: javascript jquery

有没有办法获取元素相对于窗口的当前位置,  不是文件

offset获取元素相对于文档的当前位置

3 个答案:

答案 0 :(得分:1)

要计算元素相对于视口顶边的位置,可以使用以下组合:

  • getClientBoundingRect()(确定文件中元素的位置);和
  • window.scrollY(确定窗口的垂直滚动位置)。

然后,只需从第一个值中减去第二个值:



var button = document.getElementsByTagName('button')[0];

var div = document.getElementsByTagName('div')[0];
var divRect = div.getBoundingClientRect();

function alertCurrentPosition() {
    var windowVerticalScroll = window.scrollY;
    window.alert('The top of the red square is ' + (divRect.top - windowVerticalScroll) + ' pixels below the top of the viewport');
}

button.addEventListener('click', alertCurrentPosition, false);

body {
height: 1200px;
}

button {
position: fixed;
top: 6px;
left: 6px;
}

div {
position: absolute;
top: 300px;
left: 50%;
width: 100px;
height: 100px;
background-color: rgb(255,0,0);
}

<button>Scroll the Viewport and Click Me</button>
<div></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

看到这个小提琴。 我想你会得到答案。 这是

RewriteEngine On
RewriteRule ^editar_articulo/(\w+)$ editar_articulo.php?accion=$1

答案 2 :(得分:0)

这段代码很适合我

var offset = $("selector").offset();
var posY = offset.top - $(window).scrollTop();
var posX = offset.left - $(window).scrollLeft(); 

我从这里得到答案stackoverflow.com/a/13930064/5695475

相关问题