DIV CSS 佈局教程網

讓 Div 始終浮現在螢幕正中央
編輯:關於JavaScript     

只需要兩段程式碼:一段 CSS 負責外觀,一段 JS 負責算座標。

一、先讓它出現在中間

.ordersearchDivCss {
  position: absolute;
  z-index: 100;
  display: block;
  background-color: #6ec1df;
}
<div class="ordersearchDivCss" id="DivMain"
     style="width: 400px; height: 200px" align="center"></div>

<input type="button" id="Button1" onclick="sc1('DivMain')" />

順帶一個常用的小工具函式:

// 透過元素 id 得到物件
function $(id) {
  return document.getElementById(id);
}

接著是定位的邏輯:

function sc1(DivId) {
  var Div = $(DivId);
  $(DivId).style.top = (document.documentElement.scrollTop +
    (document.documentElement.clientHeight - $(DivId).offsetHeight) / 2) + "px";
  $(DivId).style.left = (document.documentElement.scrollLeft +
    (document.documentElement.clientWidth - $(DivId).offsetWidth) / 2) + "px";
}

算式的意思很樸素:可視區域高度減去元素高度,除以二,再加上已經捲掉的距離。垂直與水平各算一次,就得到置中的座標。

二、滾動與縮放時也要維持在中間

function scall() {
  sc1("DivMain");
}

window.onscroll = scall;
window.onresize = scall;
window.onload   = scall;

三個事件缺一不可:onload 負責首次定位,onscroll 讓元素在捲動時跟著移動,onresize 則處理視窗尺寸變化——少了它,使用者一拉小提琴視窗,元素就會偏掉。

現代寫法

同樣的效果,今天只需要三行 CSS:

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

如果連 transform 都不想寫,用 Grid 或 Flexbox 置中也是一行:

body {
  display: grid;
  place-items: center;
  min-height: 100vh;
}

不過上面那段 JS 仍有學習價值:它把「如何把元素放上螢幕的任意座標」拆解成了三個可理解、可組合的數字——捲動量、容器尺寸、自身尺寸。理解了這個組合,中央、四角、距邊 20px、跟著游標偏移,都只是換一組係數而已。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved