函数的基本格式
function 函数名()
{
代码;
}
函数的定义和调用
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
function show()//定义
{
alert('abc');
}
show();//调用
</script>
</head>
<body>
</body>
</html>
简单的网页换肤代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<link id="l1" rel="stylesheet" type="text/css" href="css1.css"/>
<script>
function skin1()
{
var oL=document.getElementById('l1');
oL.href="css1.css";
}
function skin2()
{
var oL=document.getElementById('l1');
oL.href="css2.css";
}
</script>
</head>
<body>
<input type="button" value="皮肤1" onclick="skin1()"/>
<input type="button" value="皮肤2" onclick="skin2()"/>
</body>
</html>
注意:任何标签都可以加id,包括link;
任何标签的任何属性,都可以修改;
HTML里怎么写,JS里就怎么写。
简单的利用按钮在文本里改文字
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
function setText()
{
var oTxt=document.getElementById('txt1');
oTxt.value="abc";
}
</script>
</head>
<body>
<input id="txt1" type="text"/>
<input type="button" value="改文字" onclick="setText()"/>
</body>
</html>
if用作判断
if(条件)
{
语句1;
}
else
{
语句2;
}
点击按钮显示/隐藏div(弹出菜单)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
#div1{
width:100px;
height:200px;
background:#ccc;
display:none;
}
</style>
<script>
function showHide()
{
var oDiv=document.getElementById('div1');
if(oDiv.style.display=='block')
{
oDiv.style.display="none";
}
else
{
oDiv.style.display="block";
}
}
</script>
</head>
<body>
<input type="button" value="显示隐藏" onclick="showHide()"/>
<div id="div1">
</div>
</body>
</html>
className的使用(class在JS中是比较特殊的存在,不能随便拿来用,必须使用className)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
#div1
{
width:100px;
height:100px;
border:1px solid black;
}
.box{
background:red;
}
</style>
<script>
function toRed()
{
var oDiv=document.getElementById('div1');
oDiv.className='box';
}
</script>
</head>
<body>
<input type="button" value="变红" onclick="toRed()"/>
<div id="div1">
</div>
</body>
</html>