事件绑定
事件是用户或浏览器自身执行的某个动作,诸如点击click
JavaScript制作交互效果,离不开事件,所谓事件,就是用户的某个行为,能够触发一个函数的执行。
**
下面为鼠标点击事件的代码
<button οnclick="fu()">fcf</button>//鼠标点击事件: οnclick="自定义的函数名()"
<script>
function fu(){
console.log(111);
}// function函数 自定义的函数名() {
控制台输出(字符串 );
}
</script>
注意:想让控制台输出中文,需要加""
练习题
用两个按钮调整页面中红色正方形的颜色和形状
要求:按一下“变色”按钮,若原本正方形为红色,则变为绿色;若原本正方形为绿色,则变为红色。
按一下“变形”按钮,若原本为正方形则变为圆形;若原本为圆形,则变为正方形。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<title>颜色与形状切换示例</title>
<style>
//css的样式 写正方形和圆形的图形
.red-square {
width: 100px;
height: 100px;
background-color: red;
}
.green-square {
width: 100px;
height: 100px;
background-color: green;
}
.circle {
width: 100px;
height: 100px;
background-color: red;
border-radius: 50%; //表示圆形的属性代码
}
</style>
<script>
function changeColor() {// function函数 自定义的函数名() {
var square = document.getElementById('red-square');//getElementById('red-square')拿到标签的id,对声名的变量名进行赋值
if (square.className === 'red-square') {//square.className 拿到标签的class名字,判断当前class名字是否等于 'red-square',如果等于则重新赋值
square.className = 'green-square';
} else {
square.className = 'red-square';
}
}
function changeShape() {
var square = document.getElementById('red-square');
if (square.className === 'red-square' || square.className === 'green-square') {
square.className = 'circle';
} else {
square.className = 'red-square';
}
}
</script>
</head>
<body>
<div id="red-square" class="red-square"></div>
<button οnclick="changeColor()">变色</button>//鼠标点击事件:进行变色操作
<button οnclick="changeShape()">变形</button>//鼠标点击事件:进行变形操作
</body>
</html>
语法理解
if(判断条件){只有当if中的判断条件为true的时候,{ } 中的代码才能被执行,false时则不会执行if中的代码则跳过 { } 中的代码,程序继续往下执行}if 后面 () 中的判断条件,不管里面的表达式有多复杂,返回的值永远只有 true 或 false
if(){如果判断条件 为true,则执行这里的代码}else(){如果判断条件 不为true,则执行else中的代码}
if 可以单独使用,else 必须结合 if 一起使用,else指的是除了满足if条件之外的所有条件