BOM相關操作詳解
window的方法 全局函數
alert() /confirm()/ prompt() 這三個都會阻塞代碼 後兩個有返回值
window的常用子對象
location
location.href
如果不加上對應的協議 只會更改一級的字符串
location.href="www.baidu.com"
如果添加了相應的協議,就可以直接跳轉到改地址
location.href="https://www.baidu.com"
ocation.reload()刷新
location.reload(true)底層刷新
window.onclick = function(){
location.reload();
}
此時點擊頁面空白部分,頁面便會刷新。
history 前進後退的一些歷史
history.go(-1/+1)
history.back() 即history.go(-1)
history.forward() 即history.go(+1)
window.onclick = function(){
history.go(+1)
}
此時隨意點擊頁面空白部分,就會跳轉到剛纔前進過的網址。
history.length查看地址個數
console.log(history.length) ;
因爲剛纔一共有兩個網頁的跳轉,所以history.length爲2
navigator 嗅探功能
navigator.userAgent 查看當前瀏覽器版本
console.log(navigator.userAgent) ;
window的事件
onload 當瀏覽加載結束之後,包括圖片的加載,文檔資源的加載,必須全部加載結束,纔會調用
當不寫onload的時候,圖片還沒有加載完成,所以獲取不到圖片寬度。
<img src="./action_T_tit.png" alt="" id="img">
<script>
console.log(img.width);
</script>
當把這句代碼寫入onload時,就會在頁面加載之後執行,此時就可以獲取到圖片寬度。
<img src="./action_T_tit.png" alt="" id="img">
<script>
window.onload = function(){
console.log(img.width)
}
</script>
onscroll 拖動滾動條觸發此事件
當滾動條滾動觸發事件,輸出“滾動條滾動了”。
<script>
window.onscroll = function(){
console.log("滾動條滾動了")
}
</script>
onresize 窗口變化
<div id="box"></div>
<script>
window.onresize = function(){
var boxele = document.getElementById("box");
boxele.style.backgroundColor="yellow";
}
</script>
當頁面的尺寸發生了變化,方框由無色變爲黃色。
scrollTop捲動高度
document.body.scrollTop(谷歌)
document.documentElemen.scrollTopt(IE)
使用document.body.scrollTop||document.documentElement.scrollTop解決兼容問題
對於失敗的獲取 會取值爲0
對於成功的獲取 會取值爲非0
<script>
window.οnscrοll=function(){
var scrolltop = document.body.scrollTop||document.documentElement.scrollTop;
console.log(scrolltop);
}
</script>
當滾動條滾動時,輸出頁面捲動高度。
scrollTo 將頁面滾動至指定位置
1.scrollTo(0,0);
<script>
window.οnclick=function(){
scrollTo(0,0);
}
</script>
點擊瀏覽器空白部分,瀏覽器會回到頂部。
2.scrollTo({top:0,behavior:“smooth”})
<script>
window.οnclick=function(){
scrollTo({
top:0,
behavior:"smooth"
});
}
</script>
效果如上,但是有了behavior設置的運動效果,但是behavior有兼容性問題。
3.document.body.scrolltop=0,document.documentElement.scrolltop=0
<script>
window.οnclick=function(){
document.body.scrolltop=0
document.documentElement.scrolltop=0
}
</script>
效果如上,並且此方法可以解決兼容問題。
BOM操作總結
1.BOM操作是瀏覽器相關操作,是瀏覽器自帶的API。
2.瀏覽器中的提示框用alert() /confirm()/prompt() 實現,後兩個有返回值。
3.瀏覽器頁面跳轉用location.href
4.瀏覽器頁面刷新用location.reload
5.瀏覽器的前進後退用history.go(-1/+1)
6.如果有些功能想要在頁面全部加載之後再執行,就用window.οnlοad= function(){}包住
7.如果有些功能想要在頁面滾動的時候執行,就用window.onscroll = function(){}包住
8.如果有些功能想要在頁面尺寸改變的時候執行,就用window.onresize = function(){}包住
9.scrollTop是頁面的捲動高度,可以用來實現JS操縱絕對定位。
10.scrollTo 是頁面滾動至指定位置,可以用來實現回到頂部按鈕。