1.Dom操作(复习小总结)
看了dom操作好长时间了,因为没有经常用,有些遗忘,今天在复习一遍吧!又是元气满满哦,加油!
Dom 操作 是文档对象模型,跟后面讲的Bom是有区别的。
(1)事件处理器调用一个函数对事件作出反应:
<script>
function changeText( id ){
id.innerHTML = " 又是元气满满的一天";
}
</script>
<p onclick = "changeText(this)">点击查看今天心情</p>


(2)用HTML DOM 来分配点击事件
例:给button分配事件
<button id="btn">点击查看时间</button>
<p id="p"> </p>
<script>
document.getElementById("btn").onclick = function () {displayDate()};
function displayDate() {
document.getElementById("p").innerHTML = Date();
document.getElementById('btn').innerHTML = "珍惜时间哦";
}
</script>


(3)onchange()事件
onchange 事件常结合对输入字段的验证来使用。
本例就只输入后自动转换为大写,且背景色改变。( onfocus())
请输入英文字符:<input type="text" id="into"
onchange="onchange_s()" onfocus="onfocus_s(this)">
<script>
function onchange_s() {
var x = document.getElementById('into');
x.value = x.value.toUpperCase();
}
function onfocus_s(x) {
x.style.background = "#31c6c6"
}
</script>



(4)onmouseover 和 onmouseout 事件
onmouseover 和 onmouseout 事件可用于在用户的鼠标移至 HTML 元素上方或移出元素时触发函数。
eg:鼠标改变文本框内容
<div onmouseout="mout(this)" onmouseover="mover(this)">我是个有内涵的框框哦</div>
<script>
function mout(obj) {
obj.innerHTML="今天天气不错哦!"
}
function mover(obj) {
obj.innerHTML ="是个学习的好日子哦!"
}
</script>



eg:鼠标改变文本颜色
<h3 onmouseover="style.color='red'" onmouseout="style.color='blue'">
请把鼠标移到这段文本上</h3>



(5)onmousedown, onmouseup 以及 onclick
onmousedown, onmouseup 以及 onclick 构成了鼠标点击事件的所有部分。首先当点击鼠标按钮时,会触发 onmousedown 事件,当释放鼠标按钮时,会触发 onmouseup 事件,最后,当完成鼠标点击时,会触发 onclick 事件。
<div onmousedown="mDown(this)" onmouseup="mUp(this)" >请点击这里</div>
<script>
function mDown(obj){
obj.style.backgroundColor="#1ec5e5";
obj.innerHTML="请释放鼠标按钮"
}
function mUp(obj){
obj.style.backgroundColor="red";
obj.innerHTML="请按下鼠标按钮"
}
</script>



(6)dom节点的增加
方法:向 HTML DOM 添加新元素,首先必须创建该元素(元素节点),然后向一个已存在的元素追加该元素。
<div id="div1">
<p id="p1">这是一个段落</p>
</div>
<script>
创建新的 <p> 元素
var para=document.createElement("p");
如需向 <p> 元素添加文本,您必须首先创建文本节点。这段代码创建了一个文本节点
var node=document.createTextNode("这是新段落。");
然后必须向 <p> 元素追加这个文本节点
para.appendChild(node);
最后必须向一个已有的元素追加这个新元素
var element=document.getElementById("div1");
向这个已有的元素追加新元素
element.appendChild(para);
</script>
(7)dom节点的删除
方法一:找到父元素,再删除子元素
<div id="div1">
<p id="p1">这是一个段落。</p>
<p id="p2">这是要删除的段落</p>
</div>
<script>
先找到父元素:
var parent = document.getElementById("div1");
再从父元素中找到要删除的元素:
var child = document.getElementById("p2");
从父元素中删除子元素:
parent.removeChild(child);
</script>
方法二:找到要删除的子元素,然后使用其 parentNode
属性来找到父元素:
var child = document.getElementById("p2");
child.parentNode.removeChild(child);
网友评论