在窗口的右下角放置一个元素(不是视口)

时间:2015-06-08 17:48:07

标签: javascript jquery html css

我正在使用javacript将元素放置在屏幕上的某个位置(右下角)。当我调整页面大小时,我希望元素保留在右下角(视口外)。相反,我看到它移动到我的视口的右下角。

我该如何解决这个问题?

我的窗口加载功能中有以下代码:

    $('MyElement').removeClass();
    $('MyElement').css("right", "20px");
    $('MyElement').css("bottom", "55px");
    $('MyElement').css("position", "fixed");

似乎我想要与this相反,但是使用position:fixed并没有解决我的问题(我看到固定和绝对的相同行为)。

1 个答案:

答案 0 :(得分:3)

你想要position: absolute,但元素应该是body标签的直接子元素,以便它相对于body定位。您可能还需要将position: relative放在body标记上。

.thing {
  position: absolute;
  right: 20px;
  bottom: 55px;
  border: 1px solid red;
}

body {
  width: 150vw;
  height: 150vh;
  position: relative;
}
<div class="thing">Hello!</div>

$(function(){
  var op=$('.thing').offsetParent();
  var t=op.offset().top;
  var l=op.offset().left;
  var w=op.width();
  var h=op.height();
  var dh=$(document).height();
  var dw=$(document).width();
  var newbottom=t+h-dh+55;
  var newright=l+w-dw+20;
  $('.thing').css('bottom',newbottom+'px').css('right',newright+'px');
  
  });
footer {
 position: absolute;
 width: 100%;
 background-color:green;
 height: 50px;
  }
.thing {
  position: absolute;
  border: 1px solid red;
}

body {
  width: 150vw;
  height: 150vh;
  position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<footer>
<div class="thing">Hello!</div>
</footer>

相关问题