BOM浏覽器對象模型(頂級對象:window)
onload()和ready()的差別
window.onload = function(){ // 原生JavaScript 頁面加載可完畢執行的方法
}
$(document).ready(function(){ // jquery DOM元素加載完畢可執行的方法
})
$(function(){ //jquery 簡寫方式
})
兩者的差別:
1. onload(): 需要等待網頁全部加載完畢(包括圖檔等資源),然後在執行js代碼;ready():隻需要等待網頁中的DOM結構加載完即可執行js代碼
2.onload():隻可以執行一次,如果有多次,則最後一次會覆寫掉前面的js代碼;ready():可以執行多次,js代碼不會被覆寫
浏覽器視窗大小被改變的事件
window.onresize = function(){
}
localhost對象
- .hash :位址欄上#及後面的内容
- .host : 主機名及端口号
- .hostname : 主機名
- .pathname : 檔案路徑(相對路徑)
- .port : 端口号
- .portocol : 協定
- .search : 搜尋的内容
設定頁面的跳轉位址
location.href = "https://lang1427.github.io"; /*跳轉頁面位址*/
location.assign("https://lang1427.github.io");
location.reload(); /*重新加載重新整理頁面*/
location.replace("https://lang1427.github.io"); /*沒有曆史記錄的跳轉方式*/
history對象
history.forward(); /*前進*/
history.back(); /*後退,傳回上一次*/
history.go(); /*+:前進 -:後退*/
navigation對象
navigation.userAgent; /*判斷使用者浏覽器的類型*/
navigation.platform; /*判斷浏覽器所在的系統平台類型*/
定時器
var timer = setInterval(function(){ /*設定定時器*/
},1000);
window.clearInterval(timer); /*清理定時器*/
/*一次性的定時器*/
var time = window.setTimeout(function(){
},1000);
window.clearInterval(time); /*清理定時器*/
三大家族(offset、client、scroll)
JavaScript方式
offset系列:通過offset擷取style屬性中的left、top、width、height的值
<style>
*{
padding:0;
margin: 0;
/* box-sizing: border-box; */
/* 如果為盒子模型,内減模式,則offsetWidth、offsetHeight擷取到的是width、height */
}
#dv{
position: absolute;
left: 200px;
top:100px;
background-color: red;
width:200px;
height: 200px;
border:10px solid #ccc;
margin-left: 200px;
padding-left: 100px;
}
</style>
</head>
<body>
<div id="dv"></div>
</body>
<script>
console.log(document.getElementById('dv').offsetLeft)
// offsetLeft: left + margin-left的值,可視區域距離左邊的px
console.log(document.getElementById('dv').offsetTop)
// offsetTop: top + margin-top的值,可視區域距離頂部的px
console.log(document.getElementById('dv').offsetWidth)
// offsetWidth: width + border + padding,可視區域的寬度
console.log(document.getElementById('dv').offsetHeight)
// offsetHeight: height + border + padding,可視區域的高度
</script>
client系列:可視區域的寬高(内容沒有超出),左上邊框的值
.clientWidth // width + padding
.clientHeight // height + padding
.clientLeft // border的px值
.clientTop // border的px值
scroll系列:擷取實際内容或元素的寬高(内容超出需要加上超出的部分),向上向左滾出去的距離
window.onscroll = function(){ /*javascript 浏覽器的滾動事件*/
}
$(window).scroll(function(){ /*jquery 浏覽器的滾動事件*/
})
.scrollWidth // width + padding
.scrollHeight // height + padding
document.documentElement.scrollLeft // 向左滾動出去的距離
document.documentElement.scrollTop // 向上滾動出去的距離
jquery方式
.offset().left // 擷取元素相對于頁面最左側的距離 left + margin-left
.offset().top // 擷取元素相對于頁面最頂部的距離 top + margin-top
.width() // 擷取 或 設定 元素的寬度 width,與内容的寬度無關
.height() // 擷取 或 設定 元素的高度 height,與内容的高度無關
.scrollTop() // 擷取 元素向上滾動的距離值
.scrollLeft() // 擷取 元素向左滾動的距離值