- 格式:
function 函数名(参数)
{
函数体
}
函数传参 :不用var定义直接写变量名 它的类型看你传的参数是什么它就是什么
- 参数作用?
它里面参数是占位符 你传什么它就是什么(分清字符串(‘’,“”)和数字) - 什么时候用参数?
就是你要修改的样式不确定的时候用 - 问题:
2.1、如何调用函数 ?
函数名(要传的参数);
2.2、 var oDiv=document.getElementById(“div1”);不可以把这个写在函数外面
2.3 函数调用位置:可行内调用可在js里面调用
- 强调
1、分清字符串和数字
“red”字符串
‘red’字符串
red不是字符串
3、改变样式的两种方式
3.1 oDiv.style.background=
3.2 oDiv.style[backgroyund]=
3.2.1第一种 . 必须是确定的样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js函数</title>
<style>
*{
padding: 0px;
margin: 0px;
}
div{
width: 200px;
height: 200px;
background: red;
</style>
<script>
function toYellow()
{
var oDiv=document.getElementById("div1");
oDiv.style.background='Yellow';
}
function toBlue()
{
var oDiv=document.getElementById("div1");
oDiv.style.background='Blue';
}
function toPurple()
{
var oDiv=document.getElementById("div1");
oDiv.style.background='Purple';
}
</script>
<body>
<input type="button" value="变黄" onclick="toYellow()">
<input type="button" value="变蓝" onclick="toBlue()">
<input type="button" value="变紫" onclick="toPurple()">
</body>
</html>
3.2.2第二种[ ]里面是变量 他就是属性不确定的时候
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js函数</title>
<style>
*{
padding: 0px;
margin: 0px;
}
div{
width: 200px;
height: 200px;
background: red;
}
</style>
<script>
function change(name,value)
{
var oDiv=document.getElementById("div1");
oDiv.style[name]=value;
}
</script>
<body>
<input type="button" value="变宽" onclick="change('width','500px')">
<input type="button" value="变高" onclick="change('height','500px')">
<input type="button" value="变紫" onclick="change('background','purple')">
</body>
</html>
变量和字符串的区别?
–变量:值可以变
–字符串加双引号或者单引号括起来的都是写的什么就是什么
- style 和className
style控制不了class样式的
className控制class的· - 事件位置
行间事件写在行内
提取行间事件
*提取事件 :解析式从上往下便解析便执行如果把事件写在上边就会出错所以要先加载惠html–>
用window.οnlοad=function(){}加载html之后就可以添加事件
----目的:行为 样式 结构 分离
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js函数</title>
<style>
*{
padding: 0px;
margin: 0px;
}
div{
width: 200px;
height: 200px;
background: red;
}
</style>
<script>
</script>
window.onload=function()
{
var oDiv=document.getElementById("div11");
oDiv.onclick=function()
{
var oDiv1=document.getElementById("div1");
oDiv1=oDiv1.style.background='Yellow';
}
}
</head>
<body>
<form action="">
<input type="button" value="变黄" id="div11">
</form >
<div id="div1"></div>
</body>
</html>
- 同时获取多个同类型的标签
- 格式:document.getElementsByTagName(‘div’);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js函数</title>
<style>
*{
padding: 0px;
margin: 0px;
}
div{
width: 200px;
height: 200px;
background: red;
float: left;
margin-left: 20px;
}
</style>
<script>
window.onload=function()
{
var aDiv=document.getElementsByTagName('div');
alert(aDiv.length);
}
</script>
</head>
<body>
<form action="">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
- 获得后如何设置单独样式?
aDiv[0].style.background='Purple';