`

Window、Document、Element

阅读更多
 

        Windows对象是所有客户端javascript特性和API的主要接入点,它表示一个窗口或者窗体。它定义了一些属性,例如,指代Location对象的location属性,Location对象指定显示在窗口中的URL,并允许往窗口中载入新的URL

window.location = “www.baidu.com”;  //设置location属性从而跳转到新的web页面

       

 Window对象还定义了一些方法,例如alert()setTimeOut()

setTimeout(function(){alert(“hello”)},2000);  //2s后调用function弹出hello

     

Window对象中最重要的属性是document,它是Document对象,用来显示窗口中的文档。Document包含一些重要的方法。例如,getElementById()会基于元素id属性获取文档中的单一的文档元素。

 

var timestamp = document.getElementById(“timestamp”); //获取timestamp元素

 

获得的Element对象也有一些重要的方法,如获取内容,设置属性值。   

if( timestamp.firstChild == null)  //如果元素为空,往里面插入当前的时间
     timestamp.appendChild(document.createTextNode(new Date().toString));

 

  每个Element对象都有styleclassName属性,允许脚本指定元素的css属性。

timestamp.style.backgroundColor=”yellow”;
timestamp.className=”highlight”;

 

WindowDocumentElement对象都有事件处理属性,这些属性名均以“on”开头:

timestamp.onclick=function(){this.innerHTML=new Date().toString();} //单击更新内容

 

Windows对象最重要的事件处理函数之一是onload,当文档内容稳定并可以操作时,它会触发。Javascript通常封装在onload事件里。

<!DOCTYPE html>
<html>
<head>
<style>
.reveal * { display: none; }
.reveal *.handle { display: block; }
</style>
<script>
//所有的页面逻辑在onload事件后启动
window.onload=function(){
	//找到reaveal容器
	var elements=document.getElementsByClassName("reveal");
	for(var i=0;i<elements.length;i++){
		var elt=elements[i];
		//找到reaveal容器中的handle元素
		var title=elt.getElementsByClassName("handle")[0];
		addRevealHandler(title,elt);
		}
	function addRevealHandler(title,elt){
		title.onclick=function(){
			if(elt.className=="reveal"){
				elt.className="revealed";
			}
			else if(elt.className=="revealed"){
				elt.className="reveal";
			}
		}
	}
}
</script>
</head>
<body>
<div class="reveal">
<h1 class="handle"> click to hidden</h1>
<p>hidden </p>
</div>
</body>
</html>

 

<!DOCTYPE html>
<html>
<head>
<style>
#clock {
	font : bold 24pt sans;
	background : #ddf;
	padding : 10px;	
	border : solid black 2px;  
	border-radius : 10px; 
}
</style>
<script>
function displayTime(){
	var element=document.getElementById("clock");
	var now = new Date();
	element.innerHTML = now.toLocaleTimeString();
	setTimeout(displayTime,1000);  //每一秒后再执行
}
window.onload=displayTime;
</script>
</head>
<body>
<span id="clock"></span>
</body>
</html>

 

 



 

  • 大小: 2.7 KB
  • 大小: 2.7 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics