1. 回顧position屬性:static 梳侨,fixed茁彭,relative熬丧,absolute
Paste_Image.png
2.Js中的時間函數(shù):setTimeout和clearTimeout
setTimeout: 實現(xiàn)讓某個函數(shù)在經(jīng)過一段預(yù)定的時間之后才開始執(zhí)行
clearTimeout: 實現(xiàn)取消某個時間事件
3.我們來看下一個簡單的實例:通過js糕簿,改變文字的位置舵鳞。
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function moveMessage() {
//檢查
if (!document.getElementById) return false;
if (!document.getElementById("message")) return false;
//獲取到元素
var elem = document.getElementById("message");
//設(shè)置元素屬性
elem.style.position = "absolute";
elem.style.left = "200px";
elem.style.top = "100px";
}
window.onload = function () {
moveMessage();
}
</script>
</head>
<body>
<p id="message">Where!</p>
</body>
</html>
實現(xiàn)的效果如下:
Paste_Image.png
我們可以看到成功地改變了 文字的位置震檩。
思考一:為什么要設(shè)置position屬性為absolute呢?設(shè)置其他屬性可以嗎蜓堕?
我們再嘗試用setTimeout函數(shù)來實現(xiàn)顯示網(wǎng)頁3秒后抛虏,才改變文字的位置。
<script>
function moveMessage() {
//檢查
if (!document.getElementById) return false;
if (!document.getElementById("message")) return false;
//獲取到元素
var elem = document.getElementById("message");
//設(shè)置元素屬性
elem.style.position = "absolute";
elem.style.left = "200px";
elem.style.top = "100px";
}
window.onload = function () {
/**
* 第一個參數(shù)為要調(diào)用的函數(shù)名字
* 第二個參數(shù)為設(shè)定的時間套才,單位為毫秒
* 我們這里設(shè)定為3000ms嘉蕾,即3s后,會調(diào)用moveMessage()函數(shù)
*/
setTimeout('moveMessage()', 3000);
}
</script>