标签:padding 变量 声明 set click meta 背景 inpu div
1.初识函数
* 函数
* 复用代码,可以复用多行代码
*
* 函数的名字在声明的时候,尽量遵守变量的命名规则
* 函数的定义
* function 函数名(){
* //这里面的代码是要复用的代码,这里头可以放多行代码
* }
*
* 函数调用
* 函数名()
*
2.示例1
需求:
* 需求:点击任何一个按钮,改变div的宽度,高度、margin、padding、背景色等属性
*
* 分析:
* 1、获取元素(两个按钮、box)
* 2、给两个按钮添加点击事件
* 在事件里修改box的属性
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
#box{
width: 100px;
height: 100px;
background: #ff0000;
}
</style>
<script>
window.onload = function(){
var btn1=document.getElementById(‘btn1‘);
var btn2=document.getElementById(‘btn2‘);
var box = document.getElementById(‘box‘);
//给按钮添加点击事件
btn1.onclick= function (){
//点击后,要修改box的属性
box.style.width=‘200px‘;
box.style.height=‘200px‘;
box.style.margin=‘10px‘;
box.style.padding=‘20px‘;
box.style.background=‘green‘;
};
//给按钮2添加同样的事情
btn2.onclick= function (){
//点击后,要修改box的属性
box.style.width=‘200px‘;
box.style.height=‘200px‘;
box.style.margin=‘10px‘;
box.style.padding=‘20px‘;
box.style.background=‘green‘;
};
};
</script>
</head>
<body>
<input type="button" id="btn1" value="按钮1" />
<input type="button" id="btn2" value="按钮2" />
<div id="box"></div>
</body>
</html>
但是上述代码有重复,所以使用下面的代码就清爽多了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
#box{
width: 100px;
height: 100px;
background: #ff0000;
}
</style>
<script>
window.onload = function(){
var btn1=document.getElementById(‘btn1‘);
var btn2=document.getElementById(‘btn2‘);
var box = document.getElementById(‘box‘);
//给按钮添加点击事件
btn1.onclick= function (){
//点击后,要修改box的属性
setStyle();
};
//给按钮2添加同样的事情
btn2.onclick= function (){
//点击后,要修改box的属性
setStyle();
};
function setStyle(){
box.style.width=‘200px‘;
box.style.height=‘200px‘;
box.style.margin=‘10px‘;
box.style.padding=‘20px‘;
box.style.background=‘green‘;
}
};
</script>
</head>
<body>
<input type="button" id="btn1" value="按钮1" />
<input type="button" id="btn2" value="按钮2" />
<div id="box"></div>
</body>
</html>
3.匿名函数
所谓匿名函数,就是没有名字的函数。匿名函数是不能直接声明的,其总是以被赋值的形式出现的,且被事件调用;
window.onload = function(){
alert(1)
};
标签:padding 变量 声明 set click meta 背景 inpu div
原文地址:http://www.cnblogs.com/cqq-20151202/p/6618013.html