如何使用 jQuery 將 div 置中在螢幕上?


要將 div 置中在螢幕上,請使用 jQuery 居中函式 jQuery.fn.center。你可以嘗試執行以下程式碼來了解如何將 div 置中在螢幕上

示例

現場演示

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
      jQuery.fn.center = function(parent) {
        if (parent) {
          parent = this.parent();
        } else {
          parent = window;
        }
      this.css({
       "position": "absolute",
       "top": ((($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
       "left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
      });
     return this;
     }
     $("div.myclass:nth-child(1)").center(true);
     $("div.myclass:nth-child(2)").center(false);
   });
</script>
<style>
  div.box {
    width:300px;
    height:300px;
    border:2px solid #000000;
    position:relative;
    top:10px;
    left:10px;
  }
  div.myclass {
    width:50px;
    height:50px;
    color:white;
    background: #000000;
    border-radius: 4px;
    text-align:center;
  }
 </style>
</head>
<body>
  <div class="box">
    <div class="myclass">1<br>parent</div>
    <div class="myclass">2<br>window</div>
  </div>
</body>
</html>

更新於:20-6 月 -2020

628 次觀看

助力你的 職業

透過完成課程獲得認證

開始行動
廣告
© . All rights reserved.