将html元素放在页面的任何x / y坐标处

时间:2015-02-19 05:00:23

标签: javascript html css

给定X和Y坐标,我想定位一个元素,使它在屏幕/窗口的那个位置。

我希望滚动正常工作,因此固定位置不是解决方案。我想要固定的东西但是当滚动时元素应该像普通元素一样移动。

无法保证父html元素的位置是什么。也就是说它可以是静态的,相对的,绝对的或固定的。)

我理解css只有解决方案是不可能的,而且没问题。

2 个答案:

答案 0 :(得分:2)

相当于固定定位但滚动为position: absolute。它是相对于父位置的,只要它没有静态定位。

在CSS中:

#yourElement {
    position: absolute;
}

在包含xy值的JavaScript中:

var element = document.getElementById("yourElement");
element.style.left = x + "px";
element.style.top = y + "px";

答案 1 :(得分:0)

由于这个仍然是开放的,对JS Fiddle感到无聊......不确定我是否符合你想要的要求?

http://jsfiddle.net/9Lz58n3o/

示例页面

<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

.myStaticPos {
    position:absolute; 
    background-color:#d00; 
    width:32px; 
    height:32px;
}

的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")) });       
    });    
}

上面这个例子和小提琴链接是使用元素偏移的一种方式,无论滚动如何,它总是出现..否则绝对位置是绝对位置..

如果这不能满足您的需求或无法进行调整,请再次验证问题。

相关问题