1.0.3 js中DOM

1.0 通过dom对象设置内容
2.0 通过dom对象改变样式
3.0 通过dom对象添加事件
4.0 通过dom对象添加元素
5.0 通过dom对象删除元素/节点




<!DOCTYPE html>
<html>
<head>
<title>DOM对象</title>
<script type="text/javascript">
//通过document.getElementById获取元素对象
function introMethod(){
var x=document.getElementById("intro");
document.getElementById("showText").innerHTML='P标签中的内容是:' + x.innerHTML;
}
//改变样式
function updateStyle(){
var x=document.getElementById("intro");
x.style.color="#adcdef";
x.style.fontFamily="Arial";
x.style.fontSize="larger";
}
//
function showText2(){
var x=document.getElementById('intro');
var x2=document.getElementById('show2');
if(x.style.visibility=='visible'){
x.style.visibility='hidden';
x2.innerHTML="显示文本";
}else{
x.style.visibility='visible';
x2.innerHTML="隐藏文本";
}
}

//改变文本
function updateMe(thisTag){
thisTag.innerHTML="你还真点击我呀";
}

//给标签添加事件
function addEvent(){
document.getElementById("intro3").onclick=function(){showDate();};
}
function showDate(){
document.getElementById("intro3").innerHTML=new Date();
}

//鼠标事件
//鼠标滑过
function mOver(thisTag){
thisTag.innerHTML="谢谢";
}
//鼠标离开
function mOut(thisTag){
thisTag.innerHTML="把鼠标移到上面";
}
//鼠标按下
function mDown(thisTag){
thisTag.innerHTML="鼠标按下";
}
//鼠标松开
function mUp(thisTag){
thisTag.innerHTML="鼠标松开";
}
//鼠标按下事件优先于鼠标松开事件
function mclick(thisTag){
thisTag.innerHTML="鼠标点击";
}

//添加元素
function addElement(thisTag){
//创建元素
var child=document.createElement("p");
//创建文本节点
var node=document.createTextNode("这是新增的内容哦");
//向元素追加文本节点
child.appendChild(node);

var x=document.getElementById("span1");
x.appendChild(child);

}
//删除已有的节点
function delElement(thisTag){
var ps=thisTag.getElementsByTagName("p");
for(var i=0;i<ps.length;i++){
ps[i].parentNode.removeChild(ps[i]);
}

}

</script>
</head>
<body onload="addEvent()">
<div id="showText"></div><br />
<p id="intro">Hello World</p>
<p id="intro2" onclick="updateMe(this)">点击我呀</p>
<p id="intro3" >给我分配事件吧</p>
<button onclick="introMethod()">GetElementById<button>
<button onclick="updateStyle()">改变样式<button>
<button id="show2" onclick="showText2()">显示文本<button><br />
<div onmouseover="mOver(this)" onmouseout="mOut(this)" onmousedown="mDown(this)" onmouseup="mUp(this)" onclick="mclick(this)" style="background-color:green;width:120px;height:20px;padding:40px;color:#ffffff">
把鼠标移到上面
</div><br />
<span id="span1" onclick="addElement(this)">巴拉拉拉链<span>
<span id="span2" onclick="delElement(this)">
<p id="p1">这是第一个节点</p>
<p id="p2">这是第二个节点</p>
<span>

</body>
</html>



                                     @dianxinxinxiyuan.xiuyanxilu.pudongqu.shanghai

猜你喜欢

转载自listen-raining.iteye.com/blog/2275532