fixed 定位在 IE6 下的實現技巧一則

來源:互聯網
上載者:User

從藍色理想看到這貼:固定在右下角的離奇方法

受上面文章的啟發,也做了一個demo:ie6_fixed_position.html

代碼:

<div id="a" style="width: 300px; height: 100px; background: red">test</div>
<script>
var ie6 = !window.XMLHttpRequest;

var a = document.getElementById('a');
a.style.position = ie6 ? 'absolute' : 'fixed';
a.style.right = 0;
a.style.bottom = 0;

if (ie6) {
window.onscroll = function() {
a.className = a.className;
};
}
</script>

原理分析:

  1. position: absolute
    的元素,直接放在position:static
    的 body 中時,絕對位置的參考物是 body 的 viewport 部分。這使得元素 a 在視窗 resize 時,自動就能準確定位到右下角。注意:body 的 position 不能為 relative 等值,否則失效。
  2. onscroll 時需要特殊處理一下,使得滾動時,也讓絕對位置元素 a 的參考物能更新為當前的 viewport. 上面的a.className = a.className
    就是這樣一個 hack: 使得 a 的定位參考物動態更新為當前的 viewport. 類似的 hack 還有a.style.background = 'red'
    . 這些 hack 會引發 reflow, 但反之不一定,進一步的規律沒找到,不過有一個 hack,也就夠用了。

耐心總結,快樂分享,歡迎討論。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.