JS/jQ經常使用寬高及應用

關於js的寬高,隨便一搜就是一大堆。這個一大堆對我來講可不是什麼好事,看的頭都大了。因此今天就總結了一些比較會經常使用的,並說明一下應用場景。html

先來扯一下documentElement和body的微妙關係:chrome

documentElement===html  ----->>    documentElement.childNode[2]===body  【很明顯,父子關係唄】瀏覽器

若是<! doctype html>中沒聲明html,則拿不到documentElement這個值,但此時body==documentElement,這纔有了下面的兼容寫法.ide

 

ps:如下內容就只談論height,width同理嘛。工具

js的寬高及應用:動畫

可視區尺寸(.clientHeight):this

            對document:可視區height = 整個瀏覽器的高 - 工具欄部分height.firefox

                 兼容寫法:document.documentElement.clientHeight||document.documentElement.clientHeight.htm

            對div:可視區height = height + padding.文檔

             寫法:divObj.clientHeight.

滾動距離(.scrollTop):

           對document:可視區頂部到網頁頂部,即網頁被捲上去的部分.

                獲取兼容寫法:document.body.scrollTop || document.documentElement.scrollTop.

                設置兼容寫法:document.body.scrollTop = document.documentElement.scrollTop=...

           對div:div被捲上去的部分.

                獲取寫法:divObj.scrollTop.

                設置寫法:divObj.scrollTop=...

.scrollHeight:

           對document: document.body.scrollHeight被視爲整個網頁的高。【網頁內容大於clientHeight時】

                獲取寫法:document.body.scrollHeight.

          對div:沒有滾動條時,scrollHeight與clientHeight屬性結果相等,scrollWidth與clientWidth屬性結果相等;

                   存在滾動條,即存在內容溢出的狀況時,scroll屬性大於client屬性,divObj.scrollHeight包括被隱藏部分。scrollHeight可用於獲取div的wholeHeight以實現滾動到底部加載。

         【注意】scrollHeight屬性存在兼容性問題,chrome和safari瀏覽器中,scrollHeight包含padding-bottom;而IE和firefox不包含padding-bottom.

.offsetHeight:

         對document:

                  IE、Opera 認爲 offsetHeight = clientHeight + 滾動條 + 邊框。 NS、FF 認爲 offsetHeight 是網頁內容實際高度,能夠小於 clientHeight。 

         對div:

              divObj.offsetHeight=height+padding+border.

 

安利一個好東西:

.getBoundingClientRect().top/right/bottom/left;  //div的各邊距可視區的距離.

 

可視區加載:

複製代碼

1 function showDiv(){2    var showId=document.getElementById("showDiv");3    var clients=window.innerHeight||document.documentElement.clientHeigh||document.body.clientHeigh;4    var divTop=showId.getBoundingClientRect().top;
     //判斷是否出如今可視區了5    if(divTop<=clients){6       showId.classList.add('fadeInLeft');//一個帶有動畫的類7    }8 }

複製代碼

 

 

jQ的寬高及應用:

width() | height():可讀寫。(length) | function(index,oldWidth){  }

innerWidth() | innerHeight():可讀寫。(length) | function(index,oldWidth){  }

outerWidth(Boolean) | outerHeight(Boolean):爲true時包括margin,false時不包括margin.

 

.scrollTop() | .scrollLeft:被捲走的寬高。

.offset().top/left :相對於document.

.position().top/left :相對於offsetParent.

 

經常使用的屬性:

$(window).height();--可視區高

$(window).scrollTop();--滾上去的部分

$(document).height();--整個文檔的高

 

滾動到底部:

複製代碼

$(window).scroll(function(){ var scrollTop = $(this).scrollTop();    //滾動條距離頂部的高度
 var scrollHeight = $(document).height();   //當前頁面的總高度
 var clientHeight = $(this).height();    //當前可視的頁面高度
 
 if(scrollTop + clientHeight >= scrollHeight){   //滑動到底部 count++;         //每次滑動count加1
    alert("滾動底部了");
 }});

複製代碼

相關文章
相關標籤/搜索