美文网首页
JS点击变色小案例

JS点击变色小案例

作者: 白蓝青黄紫 | 来源:发表于2020-11-15 17:02 被阅读0次

版本一(行内式写法)

css部分

html,body {
        width: 100%;
        height: 100%;
        background-color:wheat;
}

html部分

<input type="button" value="点我变红" onclick="document.body.style.background='red'">

<input type="button" value="点我变蓝" onclick="document.body.style.background='blue'">

<input type="button" value="点我变黄" onclick="document.body.style.background='yellow'">

<input type="button" value="点我变绿" onclick="document.body.style.background='green'">

<input type="button" value="点我变白" onclick="document.body.style.background='#fff'">

<input type="button" value="点我变黑" onclick="document.body.style.background='rgb(0,0,0)'">

注释内容
  • input是一个标签,type="button"指它是一个按钮,value是这个按钮的内容
  • onclick是点击,点击后会执行后面的代码
  • style是样式,background是背景

版本二(函数式写法)

css部分

html,body {
        width: 100%;
        height: 100%;
        background-color:wheat;
}

HTML部分

 <button id="redBtn">红色</button>

JS部分

var redBtn = document.getElementById("redBtn").onclick = function(){
            document.body.style.background = "red"
        }

var redBtn = document.getElementById("redBtn");
redBtn. onclick = function(){
  document.body.style.background = "red"
}
注释内容
  • var redBtn 是声明一个变量,相当于给按钮起个名字存起来
  • 我们把要执行的代码放在function中存起来
  • 当我们点击这个按钮的时候,才会执行function中的代码

相关文章

网友评论

      本文标题:JS点击变色小案例

      本文链接:https://www.haomeiwen.com/subject/uiinbktx.html