1.问题:函数的定义和调用。
实现:function+函数名()
// function 函数名()
// {
// 代码
// }
// 函数名();
具体代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>定义函数和调用</title>
<script>
function show(){//定义
alert('abc');//弹出对话框显示abc。
}
show();//调用show();方法实现该函数。
</script>
</head>
<body>
</body>
</html>
2.复杂版本:实现鼠标移动到图片变色。
具体实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#div1 {
width: 200px;
height: 200px;
background-color: red;
}
</style>
<script>
function toGreen(){
//用变量把重复的代码简化
var oDiv = document.getElementById('div1');
// document.getElementById('div1').style.width='300px';
// document.getElementById('div1').style.height='300px';
// document.getElementById('div1').style.background='green';
oDiv.style.height='300px';
oDiv.style.width='300px';
oDiv.style.background='green';
}
function toRed(){
//用变量把重复的代码简化
var oDiv = document.getElementById('div1');
oDiv.style.width='200px';
oDiv.style.height='200px';
oDiv.style.background='red';
}
</script>
</head>
<body>
<!-- 古典写法 -->
<!-- <div id="div1" onmouseover="document.getElementById('div1').style.width='300px';
document.getElementById('div1').style.height='300px'
document.getElementById('div1').style.background='green'"
onmouseout="document.getElementById('div1').style.width='200px';
document.getElementById('div1').style.height='200px'
document.getElementById('div1').style.background='red'"
</div> -->
<div id="div1" onmouseover="toGreen()" onmouseout="toRed()"></div>
</body>
</html>
3.网页换肤:模拟鼠标点击网页链接实现换肤功能。
具体实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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>
其中css1.css实现的代码如下:
body{
background-color: black;
}
input{
width: 200px;
height: 100px;
background: yellow;
}
其中css2.css实现的代码如下:
body{
background-color: #ccc;
}
input{
width: 100px;
height: 50px;
background: red;
}
4.显示与隐藏:具体是点击按钮实现块级元素的显示与隐藏。
具体实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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>