設置height,width等盒模型屬性為0
這是我總結的一種比較奇葩的技巧,簡單說就是將元素的margin,border,padding,height和width等影響元素盒模型的屬性設置成0,如果元素內有子元素或內容,還應該設置其overflow:hidden來隱藏其子元素,這算是一種奇技淫巧。
~~~
.hiddenBox {
margin:0;
border:0;
padding:0;
height:0;
width:0;
overflow:hidden;
}
~~~
**一、jQuery檢測瀏覽器window滾動條到達底部**
jQuery獲取位置和尺寸**相關函數:
****$(document).height()???**?獲取整個頁面的高度
**$(window).height()???**?獲取當前也就是瀏覽器所能看到的頁面的那部分的高度。這個大小在你縮放瀏覽器窗口大小時會改變,與document是不一樣的
**scrollTop()**??? 獲取匹配元素相對滾動條頂部的偏移。
**scrollLeft()??**? 獲取匹配元素相對滾動條左側的偏移。
**scroll([[data],fn])???**?當滾動條發生變化時觸犯scroll事件
jQuery檢測滾動條到達底部代碼:
~~~
$(document).ready(function() {
$(window).scroll(function() {
if ($(document).scrollTop()<=0){
alert("滾動條已經到達頂部為0");
}
if ($(document).scrollTop() >= $(document).height() - $(window).height()) {
alert("滾動條已經到達底部為" + $(document).scrollTop());
}
});
});
~~~
**二、jQuery檢測div中滾動條到達底部**
上半篇介紹了jQuery檢測瀏覽器window滾動條到達底部,其實還并不理解scrollTop和scrollHeight概念,通常滾動條都是放在div中的。
如下檢測id為scroll_div滾動條到達底部事件:
~~~
<div id="scroll_div" style="overflow-y:auto; overflow-x:hidden;margin:100px;height:500px;border:1px solid red">
<div style="height:10000px">
來自于111111111<br>
來自于11111111111<br>
來自于1111111111<br>
</div>
</div>
~~~
?首先需要理解幾個概念:
scrollHeight:表示滾動條需要滾動的高度,即內部div,10000px
scrollTop: 表示滾動條滾動的高度,可能大于外部div 500px
也就是說scrollDiv的高度+scrollTop滾動的最大高度=scrollHeight
于是檢測div中div滾動條高度就簡單了:
~~~
$(document).ready(function() {
$("#scroll_div").scroll(function(){
var divHeight = $(this).height();
var nScrollHeight = $(this)[0].scrollHeight;
var nScrollTop = $(this)[0].scrollTop;
$("#input1").val(nScrollHeight);
$("#input2").val(nScrollTop);
$("#input3").val(divHeight);
if(nScrollTop + divHeight >= nScrollHeight) {
alert("到達底部了");
}
});
});
~~~
如果是異步加載數據,數據沒加載完,又觸犯了同一頁的數據加載請求,我通常是加一個flag
~~~
$(document).ready(function() {
var flag = false;
$("#scroll_div").scroll(function(){
if(flag){
//數據加載中
return false;
}
var divHeight = $(this).height();
var nScrollHeight = $(this)[0].scrollHeight;
var nScrollTop = $(this)[0].scrollTop;
$("#input1").val(nScrollHeight);
$("#input2").val(nScrollTop);
$("#input3").val(divHeight);
if(nScrollTop + divHeight >= nScrollHeight) {
//請求數據
flag = true;
alert("到達底部了");
}
});
});
~~~