事件绑定的笔记

事件绑定

事件是用户或浏览器自身执行的某个动作,诸如点击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条件之外的所有条件

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值