jQuery获取元素相对于窗口的位置

编程入门 行业动态 更新时间:2024-10-27 17:10:12
本文介绍了jQuery获取元素相对于窗口的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给定HTML DOM ID,如何在JavaScript / JQuery中获取元素相对于窗口的位置?这与相对于文档和偏移父项不同,因为该元素可能位于iframe或其他元素内。我需要获取元素矩形的屏幕位置(如位置和尺寸),因为它当前正在显示。如果元素当前处于屏幕外(已滚动关闭),则可以接受负值。

Given an HTML DOM ID, how to get an element's position relative to the window in JavaScript/JQuery? This is not the same as relative to the document nor offset parent since the element may be inside an iframe or some other elements. I need to get the screen location of the element's rectangle (as in position and dimension) as it is currently being displayed. Negative values are acceptable if the element is currently off-screen (have been scrolled off).

这适用于iPad(WebKit / WebView)应用程序。每当用户点击 UIWebView 中的特殊链接时,我应该打开一个弹出视图,显示有关该链接的更多信息。弹出视图需要显示一个箭头,指向调用它的屏幕部分。

This is for an iPad (WebKit / WebView) application. Whenever the user taps on a special link in an UIWebView, I am supposed to open a popover view that displays further information about the link. The popover view needs to display an arrow that points back to the part of the screen that invokes it.

推荐答案

最初,抓住 .offset 元素的位置并计算其相对于窗口的相对位置

Initially, Grab the .offset position of the element and calculate its relative position with respect to window

参考: 1. 抵消 2. 滚动 3. scrollTop

Refer : 1. offset 2. scroll 3. scrollTop

您可以试试这个 小提琴

以下几行代码说明了如何解决这个问题

Following few lines of code explains how this can be solved

执行 .scroll 事件,我们计算迟到元素相对于窗口对象的相对位置

when .scroll event is performed, we calculate the relative position of the element with respect to window object

$(window).scroll(function () { console.log(eTop - $(window).scrollTop()); });

在浏览器中执行滚动时,我们调用上面的事件处理函数

when scroll is performed in browser, we call the above event handler function

function log(txt) { $("#log").html("location : <b>" + txt + "</b> px") } $(function() { var eTop = $('#element').offset().top; //get the offset top of the element log(eTop - $(window).scrollTop()); //position of the ele w.r.t window $(window).scroll(function() { //when window is scrolled log(eTop - $(window).scrollTop()); }); });

#element { margin: 140px; text-align: center; padding: 5px; width: 200px; height: 200px; border: 1px solid #0099f9; border-radius: 3px; background: #444; color: #0099d9; opacity: 0.6; } #log { position: fixed; top: 40px; left: 40px; color: #333; } #scroll { position: fixed; bottom: 10px; right: 10px; border: 1px solid #000; border-radius: 2px; padding: 5px; }

<script src="ajax.googleapis/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="log"></div> <div id="element">Hello <hr>World</div> <div id="scroll">Scroll Down</div>

更多推荐

jQuery获取元素相对于窗口的位置

本文发布于:2023-05-30 09:20:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/365359.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:相对于   元素   窗口   位置   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!