javascript 将 html 元素定位在页面中的任何 x/y 坐标处
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28598910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Position an html element at any x/y coordinate in a page
提问by user48545
Given X and Y coordinates, I want to position an element so it's in that position on screen/window.
给定 X 和 Y 坐标,我想定位一个元素,使其位于屏幕/窗口上的那个位置。
I want scroll to work as normal, so position fixed isn't a solution. I want what fixed does but the element should move like a normal element when scrolling.
我希望滚动正常工作,因此固定位置不是解决方案。我想要固定的功能,但滚动时元素应该像普通元素一样移动。
There are no guarantees what the parent html element position will be anything. That is it can be static, relative, absolute or fixed).
不能保证父 html 元素的位置是什么。也就是说,它可以是静态的、相对的、绝对的或固定的)。
I understand css only solution is not possible and that's OK.
我明白只有 css 的解决方案是不可能的,没关系。
回答by Samuel Goodell
The equivalent of fixed positioning but with scroll is position: absolute
. It is relative to the parent position, as long as that doesn't have static positioning.
相当于固定定位但带有滚动的是position: absolute
。它是相对于父位置的,只要它没有静态定位。
In the CSS:
在 CSS 中:
#yourElement {
position: absolute;
}
And in JavaScript with x
and y
values:
在 JavaScript 中使用x
和y
值:
var element = document.getElementById("yourElement");
element.style.left = x + "px";
element.style.top = y + "px";
回答by Angry 84
Since this one is still open, got bored with JS Fiddle... Not sure if i meet the requirements of what you wanted?
由于这个仍然是开放的,对 JS Fiddle 感到无聊......不确定我是否满足您想要的要求?
Example Page
示例页面
<div>
using this div as an example of large text / body contents... can be ignored
</div>
<div class="myStaticPos" tmpleft="32" tmptop="32" style="left:32px; top:32px;"></div>
<div class="myStaticPos" tmpleft="123" tmptop="123" style="left:123px; top:123px;"></div>
CSS
CSS
.myStaticPos {
position:absolute;
background-color:#d00;
width:32px;
height:32px;
}
Javascript
Javascript
$(function() {
$(window).scroll(function() {
alignElements();
});
});
function alignElements() {
var scrollTop = $(window).scrollTop();
$( ".myStaticPos" ).each(function() {
$(this).offset({ top: scrollTop + parseInt($(this).attr("tmptop")), left: parseInt($(this).attr("tmpleft")) });
});
}
This above example and in the fiddle link is one way of using a elements offset to have it always appear regardless of scrolling.. Otherwise a position absolute is a position absolute..
这个上面的例子和小提琴链接是使用元素偏移让它总是出现而不管滚动的一种方法。否则绝对位置是绝对位置..
If this does not suite your needs or cant be adjusted, then please verify the question a little more.
如果这不适合您的需求或无法调整,请再验证一下问题。