JavaScript学习(一)——es,bom,dom
JavaScript主要由ECMAScript,BOM,DOM组成。
ECMAScript:语法规则
BOM:浏览器对象模型(使用js去操作浏览器)
DOM:文档对象模型(使用js去操作html)
BOM对象有哪些?
| 对象名称 | 说明 |
| window | 窗口对象,可以控制当前窗口,或打开新的窗口 |
| screen | 屏幕对象,获取屏幕相关信息 |
| navigator | 浏览器对象,通过这个对象可以判断用户使用的浏览器 |
| history | 历史对象,前进或后退一个页面 |
| location | 地址对象,可以获取当前url信息 |
| JavaScript计时事件 | 在一个设定的时间间隔之后来执行代码,而不是在函数被调用后立即执行 |
|
localStorage SessionStorage |
储存对象,可以用来储存数据,和cookie相似,区别是它是为了更大的容量储存设计的,使用更方便 |
弹窗:
| 弹窗 | 语法 | 说明 |
| 警告框 | window.alert() | 用于确保用户可以得到某些信息 |
| 确认框 | window.confirm() | 用于验证是否接受用户操作 |
| 提示框 | window.prompt() | 用于提示用户在进入某个页面前输入某个值 |
location:
获取当前页面地址,并把浏览器重定向到新的页面
| 语法 | 说明 |
| location.href | 返回当前页面的url |
| location.pathname | 返回url的路径名 |
| location.assign() | 加载新的文档(跳转页面) |
<html>
<head>
<title>gallery</title>
</head>
<body>
<button onclick="myFunction()">新的html跳转</button>
</body>
</html>
<script>
//document.write(location.href);//打印链接
//document.write(location.pathname);打印路径
function myFunction(){
location.assign("http://pws.paic.com.cn/m/work_gonggong.html");//跳转新的html
}
</script>
计时事件:
| 语法 | 说明 |
| setInterval() | 间隔指定的毫秒数,不停执行代码 |
| clearInterval() | 用于停止setInterval()方法执行的额函数代码 |
| setTimeout() | 暂停指定的毫秒数后执行指定的代码 |
| clearTimeout() | 用于停止执行setTimeout()方法的函数代码 |
<html>
<head>
<title>gallery</title>
</head>
<body>
<button onclick="start()">弹出</button>
<button onclick="stop()">停止</button>
<button onclick="start1()">弹出1</button>
<button onclick="stop1()">停止1</button>
</body>
</html>
<script>
var a;
var b;
function start(){
a=setInterval("alert('间隔一秒弹出内容');",1000);//一直执行
}
function stop(){
clearInterval(a);
}
function start1(){
b=setTimeout(function(){
alert("等待三秒之后弹出内容");//只执行一次
},3000);
}
function stop1(){
clearTimeout(b);
}
</script>
DOM的普通方法:
查找html元素:
| 语法 | 说明 | 注意点 |
| document.getElementById | 通过id属性获取对象 | 可以直接绑定获取的对象 |
| document.getElementsByTagName | 通过标签名获取对象 | 需要数组下标位 |
| document.getElementsByClassName | 通过Class属性获取对象 | 需要数组下标位 |
改变html元素:
| 语法 | 说明 |
| document.write() | 改变HTML输出流 |
| 对象.innerHTML = 新的HTML | 改变HTML内容 |
| 对象.attribute(比如,src,height) = 新属性值 | 改变HTML属性 |
改变css样式:
| 语法 | 说明 |
| 对象.style.property=新样式 | 更改对象css属性对应的样式 |
<html>
<head>
<title>gallery</title>
</head>
<body>
<p>输出内容</p>
<p id="old">old</p>
<img src="./1.jpg" width="200px" height="200px" id="img">
</body>
</html>
<script>
document.write("你好");//输出
document.getElementById("old").innerHTML="new";//更改内容
document.getElementById("img").src = "./2.jpg";//替换属性
document.getElementsByTagName("p")[0].style.background = "#aaa";//更改css样式
</script>
另外对于dom来说,是一个结点的树形结构。
比如document——> <html> ——> <head>/<body>
| |
v v
<title> <p>/<a>……
因此对于我们来说,可能需要需要获取结点的相应信息。
nodeValue(节点值),nodeName(节点名称),nodeType(节点类型)
其中,对于节点类型,有如下五种,我们可以通过它的默认类型值进行判断。
| 结点类型 | 结点类型值(nodeType) |
| 元素element | 1 |
| 属性attr | 2 |
| 文本text | 3 |
| 注释comments | 8 |
| 文档document | 9 |

浙公网安备 33010602011771号