Javascript:在屏幕中间显示元素dons'不要在固定的岗位上工作

Javascript: show the element in the middle of screen doesn't work with fixed postion

本文关键字:工作 中间 屏幕 显示 元素 Javascript dons      更新时间:2023-09-26

当点击按钮时,我需要元素垂直地位于屏幕的中间,无论浏览器的高度如何调整,它总是在中间。

 <html>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <button id="button">click me</button>
    <div id="element">balah</div>
    </html>

<style>
#element{
    position: fixed;
    color: red;
}
</style>

我试过了:

<script>
$("#button").click(function(){
    $('#element').css('margin-top',$(window).innerHeight()/2);
})
</script>

不需要使用JS,这可以用纯CSS完成;

.fixed {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

您也需要考虑元素来计算屏幕上的位置。。。

function FixDivCtrl() {
  var btn = $('#test');
  var target = $('#element');
  
  btn.click(function() {
    var coords = {
      "margin-top": target.height() / -2,
      "margin-left": target.width() / -2,
      "position": "fixed",
      "left": "50%",
      "top" : "50%"
    };
    target.css(coords);
  });
}
jQuery(document).ready(FixDivCtrl);
div {
  background-color: red;
  width: 50px;
  height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">Make it Fixed</button>
<div id="element"></div>

创建一个cuss类,其中Top、l、r、b设置为0px,margin:auto和position fixed。

尚未测试,但您可以使用addClass和removeClass来添加新的cuss类。

例如:$(您的元素(.addClass("center"(;

div.center {
  background-color: red;
  width: 50px;
  height: 50px;
  Top:0px;
  left:0px;
  right:0px;
  Bottom:0px;
  Position:fixed;
  Margin:auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">Make it Fixed</button>
<div id="element"></div>