w3school的HTML DOM笔记

如何改变 HTML 元素的内容 (innerHTML)

<!doctypehtml>
<html>
<head>
<meta charset="utf-8">
<title>
the first one
</title>
<script>
function displayDate(){
	document.write(Date());
}
</script>
</head>
<body style="width:500px;margin=0auto;border:1px solid red;text-align:center">
<p id="demo">this</p>
<button type="button" onclick="displayDate()">display</button>

</body>
</html>

如何改变 HTML 元素的样式 (CSS)

<!DOCTYPE html>
<html>
<body>

<p id="p1">Hello World!</p>
<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color="blue";
document.getElementById("p2").style.fontFamily="Arial";
document.getElementById("p2").style.fontSize="larger";
</script>

<p>上面的段落已被一段脚本修改。</p>

</body>
</html>


在这里插入图片描述

如何对 HTML DOM 事件作出反应

当用户在h1元素上点击时,会改变其内容:

<h1 onclick="this.innerHTML='谢谢!'">请点击该文本</h1>

提示框会告诉你,浏览器是否已启用 cookie:

<!DOCTYPE html>
<html>
<body onload="checkCookies()">

<script>
function checkCookies()
{
if (navigator.cookieEnabled==true)
	{
	alert("已启用 cookie")
	}
else
	{
	alert("未启用 cookie")
	}
}
</script>

<p>提示框会告诉你,浏览器是否已启用 cookie。</p>
</body>
</html>

若鼠标的指针在链接上移动,就产生onmouseover事件

<!DOCTYPE html>
<html>
<body>

<div onmouseover="mOver(this)" onmouseout="mOut(this)" style="background-color:green;width:120px;height:20px;padding:40px;color:#ffffff;">把鼠标移到上面</div>

<script>
function mOver(obj)
{
obj.innerHTML="谢谢"
}

function mOut(obj)
{
obj.innerHTML="把鼠标移到上面"
}
</script>

</body>
</html>

在这里插入图片描述
在这里插入图片描述

如何添加或删除 HTML 元素

添加:

<!DOCTYPE html>
<html>
<body>

<ul id="myList1"><li>Coffee</li><li>Tea</li></ul>
<ul id="myList2"><li>Water</li><li>Milk</li></ul>

<p id="demo">请点击按钮把项目从一个列表移动到另一个列表中。</p>

<button onclick="myFunction()">亲自试一试</button>

<script>
function myFunction()
{
var node=document.getElementById("myList2").lastChild;
document.getElementById("myList1").appendChild(node);
}
</script>

</body>
</html>

在这里插入图片描述
在这里插入图片描述
删除:

<!DOCTYPE html>
<html>
<body>

<div id="div1">
<p id="p1">这是一个段落。</p>
<p id="p2">这是另一个段落。</p>
</div>

<script>
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);
</script>

</body>
</html>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41949320/article/details/89764767
今日推荐