DOM的使用
问:1 DOM如何表示组成网页文档的对象?如何使用DOM对象在页面中移动对象?
DOM 文档对象模型,它是JavaScript在网页文档中引用对象的方式。
理解DOM
DOM用对象来表示页面中的每个容器及其内容,这些对象以树状结构排列,document
对象是树根,每个文本标题,段落等元素是树的叶子。
document: 1 html 1.1 head 1.2 body 1.1.1 title 1.2.1 h1 1.2.2 p
节点 文档中每个容器或元素都被称作是DOM中的一个节点。脚本经常需要引用节点,
这可以通过指定ID.
document对象是其他对象的父对象,它本身没有父对象。html对象是head和body对象
的父对象。h1和p对象是body对象的子对象。
文本节点工作方式稍有不同,段落中实际文本本身是一个节点,同时也是p对象的子
对象。同样,<h1>标签中的文本是h1对象的子对象。
head和body对象是html对象的兄弟对象。
利用<div>(或span)标签,可以高效地创建一个层(或者可以作为一个组来控制的
一组HTML对象)
设定溢出属性
overflow指明元素内容超出元素边界时,超出部分是被裁掉,还是用滚动条显示。
可以选择:visible 显示 hidden scroll auto inherit
clip 指定项目的裁剪框,只显示框内的项目内容。
display 指定条目是否在浏览器中显示,若 none 隐藏 block 显示 有换行符
inline 显示没有换行符的对象
list-item 以部分列表来显示对象
设置对象的位置和大小
position 是主要的定位属性 取以下 之一
1 static 定义的条目采用正常的HTML布局,不可移动,这是默认值。
2 absolute 指定一个条目将采用指定的坐标定位。
3 relative 指定一个条目偏离其static 位置一定距离,即偏离其在HTML页面
中正常布局位置一定距离。
z-index指定重叠的条目数量。
用JavaScipt控制定位
<div id="layer1" style="position:absolute; left:100; top:100">
<p>This is the content of the layer.</p>
</div>
var obj =document.getElementById("layer1");
obj.style.top = 200;
栗子:
<!DOCTYPE html PUBLIC "-//W3C//h2D XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/h2D/xhtml1-transitional.h2d">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Postioning Elements with JavaScript</title>
<script language="javascript" type="text/javascript"
src="miaov.js"></script>
<style>
#square {
position:absolute;
top: 150;
left: 100;
width: 200;
height: 200;
border: 2px solid black;
padding: 10px;
background-color: #E0E0E0;
}
</style>
</head>
<body>
<h1>Positioning Elements</h1>
<hr>
<form name="form1">
<input type="button" name="left" value="<-Left"
onClick="pos(-1,0);">
<input type="button" name="right" value="Right->"
onClick="pos(1,0);">
<input type="button" name="up" value="Up"
onClick="pos(0,-1);">
<input type="button" name="down" value="Down"
onClick="pos(0,1);">
<input type="button" name="hide" value="Hide"
οnclick="hideSquare();">
<input type="button" name="show" value="Show"
οnclick="showSquare();">
</form>
<hr>
<div id="square">
<p>This square is an absolutely positioned layer that you
can move using the buttons above.</p>
</div>
</body>
</html>
js:
var x = 100,y = 150;
function pos(dx,dy) {
if(!document.getElementById) return;
x += 10*dx;
y += 10*dy;
obj =document.getElementById("square");
obj.style.top=y;
obj.style.left=x;
}
function hideSquare() {
if(!document.getElementById) return;
obj = document.getElementById("square");
obj.style.display ="none";
}
function showSquare() {
if(!document.getElementById) return;
obj = document.getElementById("square");
obj.style.display ="block";
}
来源:CSDN
作者:ljt2724960661
链接:https://blog.csdn.net/ljt2724960661/article/details/102655908