当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS教程:从0开始

JS教程:从0开始

2018年12月12日  | 移动技术网IT编程  | 我要评论

一。 js简介

1. javascript概述

javascript 是世界上最流行的编程语言。这门语言可用于 html 和 web,更可广泛用于服务器、pc、笔记本电脑、平板电脑和智能手机等设备。

javascript是一种面向对象的,动态的脚本语言,主要被作为客户端脚本语言在用户的浏览器上运行,不需要编译即可运行,不需要服务器的支持。

javascript具有如下特点:

1)       javascript 是脚本语言。

2)       javascript是弱类型的语言。

3)       javascript 是一种轻量级的编程语言。

4)       javascript 是可插入html页面的编程代码。

5)       javascript 插入html页面后,可由所有的现代浏览器执行。

而我们之前学习的c#语言是服务器端语言,需要运行在服务器上。

那么我们之前学习了c#语言,为什么还要学习javascript呢?因为随着社会的发展,打开浏览器来使用web应用程序做一些业务处理已经成为主流,这也是b/s架构的应用程序取代c/s架构应用程序的原因所在。那么在浏览器里能被浏览器解析的网页语言就是html,由于html是静态的,不能处理动态的数据。而javascript可以操作html语言,实现动态数据交互功能。所以我们要学习javascript语言来弥补html语言的不足,实现动态数据的交互。

另外,在web世界里,也只有javascript能跨平台、跨浏览器驱动网页,与用户交互。

那么,我们学习javascript语言需要哪些条件呢?

1)       首先要学习html语言,这是静态网页语言,用于在网页上显示相关静态信息。

2)       再者要学习css样式,这是一种可以让html呈现的内容样式更加丰富,能呈现各种各样的效果展示数据。

2. javascript简介

2.1.      写入html输出

在vs2013中创建一个空白的web应用程序项目,asp.net web应用程序是完全支持javascript代码的编写的。

然后创建一个html页面,如图2-1所示:

 

 

图2-1

在图2-1中选择“html页”,点击“添加”按钮。如图2-2所示:

 

 

图2-2

现在我们编写第一行javascript代码:

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script type="text/javascript">

        document.write("你好!");

    </script>

</head>

<body>

 

</body>

</html>

从代码上可以看出来,javascript代码是与html代码混合在一起编写的。

1)       首先将如下代码段写在<head></head>标记内:

<script type="text/javascript">

----javascript代码段

</script>

也就是将<script>标记放在<head>标记内。然后在<script>标记中编写js代码,另外,还可以放在<body>标记内。

将上面的代码直接在浏览器里运行:

 

 

图2-3

可见,document.write()方法与c#中的response.write()方法的作用是一样的,都是在页面上输出内容,直接写入html输出。

另外,document.writeln()也是用来输出内容的,只是比write()多出一个\n,但是在浏览器中,\n被解析为空格了,所以看不到换行效果。

在html中,换行使用<br/>表示:document.write("<br/>");

所有的html代码都是可以放在document.write()方法中输出的。

<script type="text/javascript">

    document.write("<h3>欢迎学习javascript脚本语言</h3>");

    document.write("<div>姓名:<input id='name' type='text'/></div>");

    document.write("<div>年龄:<input id='age' type='text'/></div>");

    document.write("<div><input id=\"register\" type=\"button\" value=\"提交\"/></div>");

</script>

在document.write()方法中可以直接输出html代码并被浏览器解析,在双引号中可以使用单引号嵌套,还可以使用转义字符\”表示双引号。

如果要在控制台输出内容,可以使用console.log()输出,按f12可以呼出控制台,常用于输出测试数据。

 

 

 

2)       也可以将javascript代码单独放在一个.js文件中,然后在<head>或<body>标记内引用该文件:

 

 

 

图2-4

在图2-4中选择“javascript文件”,如图2-5所示:

 

 

 

图2-5

在图2-5中编写如下代码:

 

 

图2-6

然后将” javascript1.js”拖放到“htmlpage1.html”的<head>标记内:

 

 

图2-7

再次运行一下:

 

 

图2-8

如果html内容显示完成后,再使用document.write(),则会覆盖原来的内容。

2.2.      对事件的反应

javascript不仅可以将html代码直接在页面上输出,还可以对事件做出反应、改变html内容、改变html 图像、验证输入等功能。

javascript是以事件驱动的编程语言,我们可以在事件发生时执行 javascript代码,比如当用户在按钮上点击时就会触发一段javascript代码去执行。

 

 

这里添加一个input,type=“button”的按钮控件:

 

 

然后编写如下代码:

<input id="button1" type="button" value="单击我" onclick="return confirm('是否确认删除?')" />

在此代码中,我们给input标记添加了onclick属性,该属性的值就是按钮单击时触发的事件。

return confirm('是否确认删除?')

这个我们之前在asp.net webform就接触过,用来弹出确认框。

 

 

在图中单击按钮:

 

 

已经弹出确认框了,表示按钮的事件已经触发了。

在任何的html标记上都可以使用onclick执行事件。

<div onclick="getdata()">你好</div>

<span onclick="getdata()">你好</span>

<img src="" onclick="getdata()" />

<input type="button" onclick="getdata()" />·

2.3.      改变html内容

使用javascript代码可以改变html标记的内容,比如给html中的div标记改变内容。

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script type="text/javascript">

        function setvalue() {

            //所有的变量全部使用var关键字定义

            var div1 = document.getelementbyid("div1");

            //给div标记赋值

            div1.innertext = "你好";

        }

    </script>

</head>

<body>

    <div id="div1">hello</div>

    <input id="button1" type="button" onclick="setvalue()" value="赋值" />

</body>

</html>

在javascript中,所有的变量全部使用var关键字定义。

在改变html标记之前,首先要使用document.getelementbyid()方法获取该html元素,然后使用相关的属性必变元素的内容。

如果改变div标记的内容,则要使用innertext属性。将上面的代码运行:

 

 

点击一下“赋值”按钮,如下图所示:

 

 

可见,使用javascript代码已经将div标记中原来的hello内容修改为“你好“了。

1)       javascript获取文本框的值代码为:

//获取html元素

var name = document.getelementbyid("txtname");

//获取html文本框的值

window.alert(name.value);

2)       javascript给文本框赋值的代码为:

//给文本框赋值

name.value = "请输入姓名";

2.4.      改变html图像

在html中,图像标记是img。给img标记指定图像代码如下:

<img alt="这是图片" src="../images/001.png" />

使用img标记的src属性指定图片的虚拟路径。使用alt属性指定当图片不显示时显示的文本内容。

使用js改变img的图片,代码如下:

<script type="text/javascript">

    function setimgurl() {

        //获取img元素

        var img1 = document.getelementbyid("img1");

        //改变图片

        img1.src = "../images/002.png";

    }

</script>

<body>

      <img id="img1" alt="这是图片" src="../images/001.png" />

      <input id="button1" type="button" onclick="setimgurl()" value="执行" />

</body>·

 

 

点击一下按钮:

 

 

 

2.5.      验证输入

使用js代码可以在客户端验证html表单控件值的输入:

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script type="text/javascript">

        function validdata() {

            //获取html 元素的值

            var name = document.getelementbyid("txtname");

            var age = document.getelementbyid("txtage");

            //非空判断

            if (name.value != "" && age.value != "") {

                document.write("验证通过!");

            }

            else {

                alert("用户名和密码不可为空!");

            }

        }

    </script>

</head>

<body>

    姓名:<input type="text" id="txtname" />

    年龄:<input id="txtage" type="text" />

    <input id="button1" type="button" onclick="validdata()" value="提交" />

</body>

</html>

 

 

 

 

如果要验证在文本框中输入的字符是否是数字,可以使用isnan()方法来判断,

当isnan()=true,表示输入的不是数字,当isnan()=false,表示输入的是数字:

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script>

        function isnumber() {

            var n = document.getelementbyid("text1");

            if(n.value=="" || isnan(n.value)){

                alert('您输入的不是数字,请重新输入!');

            }

        }

    </script>

</head>

<body>

    <input id="text1" type="text" />

    <input id="button1" type="button" value="测试是否为数字" onclick="isnumber()" />

</body>

</html>

 

 

3. javascript用法

对于script标记,在html中有两种用法:

1)       在html代码中嵌入javascript代码:

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script type="text/javascript">

        document.write("你好");

        document.write("hello");

    </script>

</head>

一般是在<head>标记内使用<script>标记来嵌入javascript代码在html代码中,当然也可以在<body>标记内使用<script>标记。

2)       使用script标记引用外部的*.js文件:

 

 

 

在js文件内,只编写js代码即可。

由于浏览器是从上到下的顺序执行html代码的,所以如果<head>标记内包含大量的javascript代码,则可能网页的加载速度就会变慢,此时,可以将js代码放在<body>标记的底部,以加快网页的加载速度。

 

 

4. javascript语法简介

4.1.      javascript语法

javascript是一种轻量级的脚本语言,并且是弱类型语言,而c#是强类型的语言。之所以称为弱类型语言,是因为定义的变量可以存储任意类型的数据。

在javascritp中,变量全部统一使用var关键字来定义。

<script type="text/javascript">

    var x1 = 100;

    x1 = "abc";

    x1 = true;

</script>

在此处先使用var定义了变量x1,并赋值为100,后来又赋值了字符串”abc”和布尔类型true,这就是弱类型的表现。这在c#中是不会允许的。最终x1变量的值就是true。

javascript语言是区分大小写的。

并且标识符只能以字母、下划线和美元符号$开头,并且也不能是关键字和保留字,但标识符中可以包含保留字和关键字。

4.2.      函数的定义和使用

javascript中的函数可以理解为c#中的方法,都是用来封装功能的段码段。

javascript函数的定义都是使用function关键字定义的:

function f1() {

    alert("这是函数");

}

javascript函数不需要定义返回类型,但有返回值,有返回值时使用return语句返回即可:

function f2() {

    return "你好";

}

javascript函数也可以带有参数,但不需要指定参数类型,只需要参数名即可:

function f3(str1, str2, number1, b1) {

    return str1 + str2 + number1 + b1;

}

还有另外一种定义函数的方法:

var f4 = function () {

    return "hello";

}

这种形式的定义也是正确的。

定义的函数就可以直接调用了,一般会在html元素的事件中调用:

<body>

    <input id="button1" type="button" value="button" onclick="f1()" />

    <input id="button1" type="button" value="button" onclick="f3('a','b',100,true)" />

    <input id="button1" type="button" value="button" onclick="f4()"/>

</body>

4.3.      常的html事件

常见的html事件有:单击事件onclick、鼠标移至html元素上onmouseover、鼠标离开html元素onmouseout等。

<body>

    <input id="button1" type="button" value="button" onmouseover="f2()" onclick="f1()" />

    <input id="button1" type="button" value="button" onmouseout="f1()" onclick="f3('a','b',100,true)" />

    <input id="button1" type="button" value="button" onclick="f4()"/>

</body>

4.4.      javascript关键字和保留字

javascript关键字用于标识要执行的操作,和其他任何编程语言一样,javascript 保留了一些关键字为自己所用。

下面是javascript中的关键字和保留字:

 

 

4.5.      注释

单行注释使用//表示。

多行注释或块注释使用/*   */表示。

 

 

二。 javascript浏览器对象bom

 

1. 概述

bom称为浏览器对象模型,主要用来对浏览器进行相关的操作,有了bom,才使javascript可以操作浏览器的相关对象,例如:打开窗口、关闭窗口,弹出提示框等等。

浏览器对象模型(browser object model (bom))尚无正式标准,但现代的浏览器都支持bom。

2. window对象

2.1.      基本概念

浏览器对象模型 (bom) 使 javascript 有能力与浏览器“对话”。由于现代浏览器已经(几乎)实现了 javascript 交互性方面的相同方法和属性,因此常被认为是 bom 的方法和属性。

常见的alert()、confirm()都属于window对象的方法。

全局变量是 window 对象的属性。全局函数是 window 对象的方法。

 

 

定义的全局变量x已经成为window对象的属性。

 

 

定义的全局函数成为了window对象的方法。

2.2.      window尺寸

有三种方法能够确定浏览器窗口的尺寸(浏览器的视口,不包括工具栏和滚动条)。

对于internet explorer10、chrome、firefox、opera 以及 safari:

    window.innerheight - 浏览器窗口的内部高度

    window.innerwidth - 浏览器窗口的内部宽度

对于 internet explorer 8、7、6、5:

    document.documentelement.clientheight

    document.documentelement.clientwidth

或者

    document.body.clientheight

document.body.clientwidth

那么兼容通用的获取浏览器的窗口高度和宽度:

<script>

var w=window.innerwidth

|| document.documentelement.clientwidth

|| document.body.clientwidth;

 

var h=window.innerheight

|| document.documentelement.clientheight

|| document.body.clientheight;

 

x=document.getelementbyid("demo");

x.innerhtml="浏览器的内部窗口宽度:" + w + ",高度:" + h + "。"

</script>

2.3.      其它window方法

这些属性有的是对open()打开的窗口生效。

1)       window.open() :打开新窗口。

<script type="text/javascript">

    function openwin() {

        window.open("htmlpage1.html");

    }

</script>

2)       window.close() :关闭当前窗口。

function closewin() {

    window.close();

}

3)       window.moveto() :移动窗口。

<script type="text/javascript">

    var w;

    function openwindow() {

        w = window.open("htmlpage1.html", "", "width=200,height=100");

    }

    function movewindow() {

        w.moveto(300, 400);

    }

</script>

moveto() 方法可把窗口的左上角移动到一个指定的坐标。

4)       window.resizeto() :调整窗口的尺寸。

   <script type="text/javascript">

    var w;

    function openwindow() {

        w = window.open("htmlpage1.html", "", "width=200,height=100");

    }

    function movewindow() {

        w.moveto(300, 400);

    }

    function resizewindow() {

        w.resizeto(400, 600);

    }

</script>

resizeto()把窗口大小调整为指定的宽度和高度。

3. window.screen

window.screen 对象包含有关用户屏幕的信息。window.screen 对象在编写时可以不使用 window 这个前缀。

 

 

1)       availheight:获取屏幕(不是浏览器)的可用高度,不包括任务栏,单位是像素。

2)       avaiwidth:获取屏幕(不是浏览器)的可用宽度,不包括任务栏,单位是像素。

3)       colordepth:返回屏幕的色彩,也就是屏幕调色板的比特深度,现在大部分都是24色。

4)       height:返回屏幕的总高度,包括任务栏。

5)       pixeldepth:返回屏幕颜色的分辨率,每像素的位数,例如:24位。

6)       width:返回屏幕的总宽度,包括任务栏。

<script>

    var awidth = window.screen.availwidth;

    var aheight = window.screen.availheight;

    document.write("可用宽度是:" + awidth);

    document.write("可用高度是:" + aheight);

</script>

 

 

由于当前电脑的分辨率是1366*768,由于高度不包括任务栏,所以可用高度变成了728,这说明任务栏的高度是40。

4. window.location

window.location对象用于获得当前页面的地址 (url),并也可把浏览器重定向到新的页面。

 

 

1)       hash:返回url的锚部分,也就是url含#及后面的内容。

 

 

2)       host:返回url的主机名和端口号:

 

 

 

3)       hostname:返回url的主机名:

 

 

4)       port:返回url的端口号:

 

 

5)       protocol:返回url的web协议:

 

 

6)       search:返回url的查询部分:

 

4.1.      href

使用window.location.href可以获取当前浏览器的完整页面地址。

<script type="text/javascript">

    var strhref = location.href;

    document.write(strhref);

</script>

 

 

也可以给location.href赋值url地址实现页面的重定向。如下代码:

window.location.href = "http://baidu.com";

window.location.href = "htmlpage1.html";

4.2.      pathname

location.pathname 属性返回url的路径名(不包含域名和端口号)。

<script>

    var pathname = location.pathname;

    document.write(pathname);

</script>

 

 

4.3.      assign

location.assign() 方法加载新的文档。

<script>

    location.assign("http://baidu.com");

    location.assign("htmlpage1.html");

</script>

location.assign()方法与location.href属性实现的效果是一样的,都是重定向到新的页面。

location对象的其它方法和属性:

1)       location.hostname 返回 web 主机的域名

2)       location.pathname 返回当前页面的路径和文件名

3)       location.port 返回 web 主机的端口 (80 或 443)

4)       location.protocol 返回所使用的 web 协议(http:// 或 https://)

5. window.history

window.history对象包含浏览器的历史记录。

 

 

window.history 对象在编写时可不使用 window 这个前缀。

为了保护用户隐私,对 javascript 访问该对象的方法做出了限制。

常用的一些方法:

1)       history.back() - 与在浏览器点击后退按钮相同,加载历史列表中的前一个 url。

2)       history.forward() - 与在浏览器中点击前进按钮向前相同,history.forward() 方法加载历史列表中的下一个 url。

//后退

history.back();

//前进

history.forward();

3)  history.go():加载history列表中某个具体的页面,加载的页面必须是历史访问过的。

该参数可以是数字,使用的是要访问的 url 在 history 的 url 列表中的相对位置。(-1上一个页面,1下一个页面)。或一个字符串,字符串必须是局部或完整的url,该函数会去匹配字符串的第一个url。

go(-1): 返回上一页,原页面表单中的内容会丢失;

back(-1): 返回上一页,原页表表单中的内容会保留。

window.history.go(-2)表示后退2页。

6. window.navigator

window.navigator对象包含有关访问者浏览器的信息。

navigator.appname用于获取浏览器的名称。

 

 

1)       appcodename:返回浏览器的代码名,目前主流的浏览器(ie11/edge/firefox/google chrom)的appcodename都是:mozilla。

2)       appname:返回浏览器的名称。目前主流的浏览器(ie11/edge/firefox/google chrom)的appname都是:netscape。

3)       appversion:返回浏览器的平台和版本信息。每个浏览器返回的信息不一样。

 

 

 

 

firefox

 

 

edge

4)       cookieenabled:返回当前浏览器是否启用了cookie。目前浏览器大都支持cookie,返回true。

5)       platform:返回运行浏览器的操作系统。如果运行的是windows操作系统,则返回win32。

6)       useragent:返回客户端发送服务器的用户代理字符串。每个浏览器返回的值不太一样。

7. 弹窗

7.1.      警告框

javascript中的警告框使用window.alert()方法来实现。显示带有一段消息和一个确认按钮的警告框。

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script type="text/javascript">

        function alertpage() {

            if (text1.value == "") {

                window.alert("用户名不能为空!");

            }

        }

    </script>

</head>

<body>

   用户名:<input id="text1" type="text" />

    <input id="button1" type="button" value="弹出" onclick="alertpage()" />

</body>

</html>

 

 

7.2.      确认框

确认框使用confirm()方法表示,显示带有一段消息以及确认按钮和取消按钮的对话框。

注意:confirm()会返回一个布尔类型的值,如果返回的值为true,则表示用户点击了“确定”按钮,否则点击了“取消”或关闭按钮。

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script>

        function confirmpage() {

            var b = window.confirm("是否确认删除?");

            if (b == true) {

                document.write("确认需要删除!")

            }else

            {

                document.write("不需要删除!");

            }

        }

    </script>

</head>

<body>

    <input id="button1" type="button" onclick="confirmpage()" value="删除" />

</body>

</html>

 

 

当点击了“确定”按钮。

 

 

7.3.      提示框

提示框使用prompt()方法表示,prompt()方法用于显示可提示用户进行输入的对话框。这个方法返回用户输入的字符串。

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script type="text/javascript">

        function promptpage() {

            var x = window.prompt("请输入您的姓名");

            document.write(x);

        }

    </script>

</head>

<body>

    <input id="button1" type="button" onclick="promptpage()" value="弹出" />

</body>

</html>

 

 

 

 

 

 

如果没有在文本框中输入任何内容,则接收的值为null。

7.4.      换行

在html中,可以使用的换行有:<br/>,还可以使用<p/>。

但是在javascript的所有弹窗中要使用换行,则要使用\n实现:

var x = window.prompt("请输入您的姓名:\n包含全名");

 

 

8. 计时事件

通过使用 javascript,我们有能力做到在一个设定的时间间隔之后来执行代码,而不是在函数被调用后立即执行。我们称之为计时事件。

8.1.      settimeout()方法

settimeout()方法也称为超时调用。用于在指定的毫秒数之后执行一段javascript代码,只执行一次,其语法如下:

var t=settimeout("javascript语句",毫秒)

注意:1000毫秒等于1秒。

案例:当按钮被点击时,一个提示框会在5秒中后弹出。

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script type="text/javascript">

        function settimeoutdemo(){

         window.settimeout("alert('您好!')", 5000);

        }

    </script>

</head>

<body>

    <input id="button1" type="button" onclick="settimeoutdemo()" value="确定" />

</body>

</html>

一般情况下,我们会给settimeout()方法第1个参数传递一个函数,而不是js代码。如下代码:

<script type="text/javascript">

    function settimeoutdemo(){

        //window.settimeout("alert('您好!')", 5000);

        window.settimeout(function () {

            window.alert("hello");

        }, 5000);

    }

</script>

8.2.      cleartimeout()方法

如果要取消settimeout()方法执行的代码,可以使用cleartimeout()。

<script type="text/javascript">

    function settimeoutdemo(){

        //window.settimeout("alert('您好!')", 5000);

        var timeoutid = window.settimeout(function () {

            window.alert("hello");

        }, 5000);

        //取消执行

        window.cleartimeout(timeoutid);

    }

</script>

cleartimeout()方法需要一个超时id。

8.3.      setinterval()和clearinterval()方法

setinterval() 方法可按照指定的周期(以毫秒计)来重复调用函数或计算表达式。

setinterval()也称为间隔调用。如果不停止,就是死循环,无限循环。

setinterval() 方法会不停地调用函数,直到 clearinterval() 被调用或窗口被关闭。由 setinterval() 返回的id值可用作 clearinterval() 方法的参数。

基本语法如下:

setinterval("javascript语句",毫秒)

案例:模拟时钟

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script type="text/javascript">

        //时钟开始

        var id;

        function start() {

var div1 = document.getelementbyid("div1");

            id = setinterval(function () {

               

                div1.innertext = new date();

            },1000);

        }

        function end() {

            clearinterval(id);

        }

    </script>

</head>

<body>

    <div id="div1"></div>

    <input id="button1" type="button" onclick="start()" value="开始" />

    <input id="button2" type="button" onclick="end()" value="停止" />

</body>

</html>

 

 

三。 javascript  html dom操作

1. dom简介

1.1.      基本概念

html dom称为文档对象模型,当网页被加载时,浏览器会创建页面的文档对象模型(document object model)dom。

html dom 模型被构造为对象的树。

 

 

通过可编程的文档对象模型,javascript 获得了足够的能力来创建动态的 html。

1)       javascript 能够改变页面中的所有 html 元素

2)       javascript 能够改变页面中的所有 html 属性

3)       javascript 能够改变页面中的所有 css 样式

4)       javascript 能够对页面中的所有事件做出反应

1.2.      查找html元素

在javascript中,如果想要操作html元素,则首先必须要找到该元素,查找到html元素之后就变为对象,那么给对象赋值和获取值就可以操作html元素了。

javscript能够操作html元素,就是通过dom来实现的。

1.2.1.   通过id找到html元素

在html中,所有的标记都可以具有一个唯一的id值,通过这个id值就可以轻松的找到该html元素。

在dom中查找html元素的最简单的方法,就是通过使用元素的 id值。如果未找到,则返回null,如果找到,则返回该元素的对象。如果存在id相同的,则只查找到第1个html元素。

基本语法如下:

var 变量名= document.getelementbyid("html元素的id值");

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script type="text/javascript">

        //查找到id为div1的div元素

        var div1 = document.getelementbyid("div1");

        //查找id为p1的p元素

        var p1 = document.getelementbyid("p1");

        //查找id为span1的span元素

        var span1 = document.getelementbyid("span1");

        //查找id为button1的button元素

        var button1 = document.getelementbyid("button1");

    </script>

</head>

<body>

    <div id="div1">

        <p id="p1">

            <span id="span1">

                <input id="button1" type="button" value="button" />

            </span>

        </p>

    </div>

</body>

</html>

1.2.2.   通过标签名查找html元素

html标记的标签名是指某一类html元素,例如:p标签名表示所有的p元素,div标签名表示所有的div元素。

通过标签名可以在整个html dom树中遍历所有的html元素,从而按标签名查找,返回的结果是一个包含相同标签名的元素集合。

基本语法如下:

var 集合名= document.getelementsbytagname("标签名");

注意:getelementsbytagname()方法返回的是一个包含多个元素的集合。

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script type="text/javascript">

        var tagnames = document.getelementsbytagname("p");

        console.log(tagnames);

    </script>

</head>

<body>

    <div id="div1">

        <div>

            <p id="p1">你好</p>

        </div>

    </div>

    <div id="div2">

        <div>

            <p id="p2">hello</p>

        </div>

    </div>

</body>

</html>

 

 

可见,在图中,getelementsbytagname()返回的类型是htmlcollection集合。其中的length属性可以获取一共查找到了多少个元素。通过索引值可以获取查找到的元素对象。索引值是从0开始的,当然也可以通过id值查找。htmlcollection[“id”]。

1.2.3.   通过name查找html元素

通过html元素的name属性值查找html元素,使用getelementsbyname() 方法。由于在html代码中,有的元素的name值可能会相同,所以

getelementsbyname()方法返回的是一个nodelist集合。

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script>

        function getname() {

            var name = document.getelementsbyname("btnname");

            console.log(name.value);

        }

    </script>

</head>

<body>

    <div id="div1">

        <input type="text" id="btnid" name="btnname" />

        <input type="text" id="btnid" name="btnname" />

        <input type="text"  id="txtid" name="txtage"/>

    </div>

</body>

</html>

1.2.4.   通过类名找到html元素

这里说的类名是指css中的类名。这样我们就可以通过css的类名来查找html元素,使用getelementsbyclassname()方法,返回的是一个htmlcollection集合。

基本语法如下:

var 集合名= document.getelementsbyclassname("类名");

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script type="text/javascript">

        function getclassname() {

            var classname = document.getelementsbyclassname("topdiv");

            console.log(classname);

        }

    </script>

    <style type="text/css">

        .topdiv{

            width:200px;

            line-height:30px;

            height:30px;

        }

    </style>

</head>

<body>

    <div id="div1" class="topdiv">

        <div id="div11" class="topdiv"></div>

    </div>

    <div id="div2" class="topdiv">

        <div id="div21"></div>

    </div>

    <input id="button1" type="button" value="查找" onclick="getclassname()" />

</body>

</html>

 

 

2. dom html

html dom允许javascript改变html元素的内容。

1)       改变html输出流

在javascript中,使用document.write() 可直接向 html 输出流写内容。注意:document.write()会将页面上原来的内容全部覆盖掉。

document.write(new date().todatestring());

2)       改变html内容

对于html元素的内容,可以使用innerhtml和innertext这两个属性获取或赋值。

innerhtml属性可以设置带有html标记的内容:

div1.innerhtml= "<span style='color:red'>你好</span>";

innertext属性只能设置纯文本内容:

div1.innertext = "你还好吗?";

3)       改变html属性的值

改变html属性是指可以修改属性的值,从而达到不同的效果。

//将div1元素的id值修改为div2

div1.id = "div2";

最常用的还有一种就是改变图片的地址,从而达到切换图片的效果:

document.getelementbyid("img1").src = "/images/003.png";

 

3. dom css

html dom允许javascript改变html元素的样式。

要想改变html元素的样式,则还是需要查找到该元素,然后使用如下语法改变样式:

document.getelementbyid(id).style.属性名=新样式

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script>

        function editcss() {

            //查找到该元素

            var div1 = document.getelementbyid("div1");

            //改变样式

            div1.style.color = "blue";

        }

    </script>

</head>

<body>

    <div id="div1" style="color:red">你好</div>

    <input id="button1" type="button" value="执行" onclick="editcss()" />

</body>

</html>

 

4. dom 事件

4.1.      基本概念

html dom使javascript有能力对html事件做出反应。可以在事件发生时执行javascript代码,例如当用户在html元素上点击时。

html具有的事件如下:

1)       当用户点击鼠标时

2)       当网页已加载时

3)       当图像已加载时

4)       当鼠标移动到元素上时

5)       当输入字段被改变时

6)       当提交 html 表单时

7)       当用户触发按键时

4.2.      html事件属性

如需向html元素分配事件,可以使用事件属性,事件属性大都以on开头。

 

 

在vs开发工具中,所有以闪电图标出现的都是事件。

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script type="text/javascript">

        function f1() {

 

        }

    </script>

</head>

<body>

    <input id="button1" type="button" value="button" onclick="f1()" />

</body>

</html>

事件属性的值都是以函数的形式出现的,也就是直接调用函数。

4.3.      使用html dom来分配事件

html dom 允许通过使用javascript来向html元素分配事件。在上图中,我们都是直接在html标记上写事件属性,是在html代码中指定的。当然也可以在js代码中指定:

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

</head>

<body>

    <input id="button1" type="button" value="button" />

    <script type="text/javascript">

        //向button1分配onclick事件

        document.getelementbyid("button1").onclick = function () {

            document.write("单击了按钮。");

        }

    </script>

</body>

</html>

在此代码中,使用js代码给按钮分配了onclick事件属性,并且还指定事件代码,是一个匿名的函数。

在这里,我们将js代码放在了按钮的后面,这是因为js代码首先要查找按钮,只有查找到之后才可以分配事件。

4.4.      onload和onunload事件

onload 和 onunload 事件会在用户进入或离开页面时被触发。

onload 事件可用于检测访问者的浏览器类型和浏览器版本,并基于这些信息来加载网页的正确版本。

onload 和 onunload 事件可用于处理 cookie。

一般会在<body>标记上使用onload和onunload事件。

4.5.      onchange事件

onchange事件常结合对输入字段的验证来使用。

当输入的内容发生改变时则触发onchange事件。

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script>

        function isemptystring(str) {

            if (str.value == "") {

                alert("用户名不能为空");

            }

        }

    </script>

</head>

<body>

   用户名: <input id="text1" type="text"  onchange="isemptystring(this)"/>

</body>

</html>

 

 

 

 

4.6.      onmouseover 和 onmouseout 事件

onmouseover和onmouseout事件可用于在用户的鼠标移至html 元素上方或移出元素时触发函数。

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script type="text/javascript">

        function overcolor() {

            var t = document.getelementbyid("text1");

            t.style.border = "1px solid #ddd;";

            t.style.color = "blue";

            t.style.backgroundcolor = "#ccc";

        }

        function outcolor() {

            var t = document.getelementbyid("text1");

            t.style.border = "";

            t.style.color = "";

            t.style.backgroundcolor = "";

        }

    </script>

</head>

<body>

    <input id="text1" onmouseover="overcolor()" onmouseout="outcolor()" type="text" />

</body>

</html>

 

 

上图是默认的效果。

 

 

 

上图是鼠标移至文本框上之后触发了onmouseover事件,执行了overcolor()函数中的代码。

 

 

上图是鼠标离开了文本框时触发了outcolor()事件。

4.7.      onmousedown、onmouseup 以及 onclick 事件

onmousedown, onmouseup 以及 onclick 构成了鼠标点击事件的所有部分。首先当点击鼠标按钮时,会触发 onmousedown 事件,当释放鼠标按钮时,会触发 onmouseup 事件,最后,当完成鼠标点击时,会触发 onclick 事件。

注意:鼠标按下、鼠标释放包括左键和右键。但对于onclick事件,则只是鼠标左键单击时触发。

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title></title>

    <script type="text/javascript">

        //当鼠标按下时

        function down() {

            var btn = document.getelementbyid("button1");

            btn.value = "鼠标已按下";

        }

        //当鼠标松开时

        function up() {

      &n

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网