如何在缩放时在IOS浏览器上定位固定位置元素? [英] How to position a fixed-location element on IOS browser when zoomed?
问题描述
我有一个很好的小 React拖放库可以工作用于鼠标和触摸系统。对于触摸,它通过 clientX
和 clientY
( e.targetTouches [0]抓取触摸位置] .clientX,e.targetTouches [0] .clientY
)。它使用这些坐标来放置被拖动的元素,其中 position:fixed
。
I have a nice little React drag-drop library that works for mouse- and touch systems. For touch, it grabs the touch location via clientX
and clientY
(e.targetTouches[0].clientX, e.targetTouches[0].clientY
). It uses those coordinates to place the dragged element, which has position: fixed
.
但是,结果是至少在IOS Safari(v.11.x)上,当你缩放显示时,坐标系的位置:fixed不再与窗口坐标系匹配。因此,拖动的元素显示在页面上的错误位置。
HOWEVER it turns out that at least on IOS Safari (v.11.x), when you zoom the display, the coordinate system for position:fixed no longer matches the window coordinate system. So the dragged element displays in the wrong place on the page.
将放大的浏览器窗口画成一个小矩形视图,放在包含未缩放内容的较大矩形上。位置:固定坐标系使用较大的矩形。窗口坐标系使用小坐标系。
Picture the zoomed-in browser window as a small rectangular view onto a larger rectangle containing the un-zoomed content. The location:fixed coordinate system uses the larger rectangle. The window coordinate system uses the small one.
当你滚动时,窗口以一种难以描述的方式在较大的矩形周围平移,结果在位置固定的土地上偏移0,0浏览器窗口中的0,0总是在变化。
As you scroll, the window pans around the larger rectangle in a way that's difficult to describe, with the result that the offset between 0,0 in position-fixed-land and 0,0 in the browser window is always changing.
如何获得浏览器窗口和位置:固定坐标系之间的偏移量? (然后我可以将该偏移量添加到被拖动元素的位置以正确定位它。)
How can I get the offset between the browser window and the "position:fixed" coordinate systems? (I can then add that offset to the position of the dragged element to position it correctly.)
推荐答案
将元素粘贴在0 ,0,位置:固定。
Stick an element at 0,0, position:fixed.
使用 getBoundingClientRect()
从浏览器窗口获取x / y偏移量。
Get its x/y offset from the browser window using getBoundingClientRect()
.
然后删除元素。
function getFixedOffset() {
let fixedElem = document.createElement('div');
fixedElem.style.cssText = 'position:fixed; top: 0; left: 0';
document.body.appendChild(fixedElem);
const rect = fixedElem.getBoundingClientRect();
document.body.removeChild(fixedElem);
return [rect.left, rect.top]
}
这是有效的(耶!)但感觉相当笨拙,每次用户拖放时创建然后销毁DOM元素。欢迎提出其他建议。
This works (yay!) but feels pretty kludgey, creating and then destroying a DOM element every time the user drags-and-drops. Other suggestions are welcome.
这篇关于如何在缩放时在IOS浏览器上定位固定位置元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!