1.在HTML文件中写JS方法
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb18030">
<title>插入js代码</title>
<script type="text/javascript">
document.write("开启JS之旅!");
</script>
</head>
<body>
</body>
</html>
2.在HTML中调用JS文件
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>引用JS文件</title>
<script src="script.js"></script>
</head>
<body>
</body>
</html>
3.调用JS函数
//定义函数
<script type="text/javascript">
function contxt() //定义函数
{
alert("哈哈,调用函数了!");
}
</script>
//调用
<input type="button" value="点击我" onclick="contxt()" />
4.JS位置
一般放在body或head里面。
5.输出
<script type="text/javascript">
var mystr="我是";
var mychar="JS";
document.write(mystr+"<br>");
document.write(mystr+mychar+"金城!");
</script>
6.alert警告框
alert(字符串或变量)
function rec(){
var mychar="Learn JavaScript";
alert(mychar);
alert("hello!");
}
//依次弹出"Learn JavaScript","hello"警告框
7.confirm消息确认框
confirm();
//str:显示的文本
//返回值:boolean值
8.prompt消息对话框
prompt("你好","123");
//返回值是"123"
9.打开新窗口
window.open('http://www.imooc.com','_blank','width=300.height=200,menubar=no,toolbar=no,status=no,scrollbars=yes');
10.关闭窗口
window.close();//关闭窗口
<窗口对象>.close();//关闭指定窗口
11.使用
<!DOCTYPE html>
<html>
<head>
<title> new document </title>
<meta http-equiv="Content-Type" content="text/html; charset=gbk"/>
<script type="text/javascript">
function openWindow(){
// 新窗口打开时弹出确认框,是否打开
var url;
if(confirm("你好")){
// 通过输入对话框,确定打开的网址,默认为 http://www.imooc.com/
url = prompt("打开网址","http://www.imooc.com/")
}
//打开的窗口要求,宽400像素,高500像素,无菜单栏、无工具栏。
window.open(url,'_blank','width=400,height=500,status=no,toolbar=no')
}
</script>
</head>
<body>
<input type="button" value="新窗口打开网站" onclick="openWindow()" />
</body>
</html>
12.控制类名
object.className = classname
//设置CSS样式
<style>
body{ font-size:16px;}
.one{
border:1px solid #eee;
width:230px;
height:50px;
background:#ccc;
color:red;
}
.two{
border:1px solid #ccc;
width:230px;
height:50px;
background:#9CF;
color:blue;
}
</style>
//使用
var p1 = document.getElementById("p1");
p1.className="one";
//========================
Object.style.property=new style;
Object.style.display = value;