基础网页特效开发

一、树形菜单

树形菜单是网页中经常见到的一种动态效果,开发流程如下:

创建网页文件:demo01treemenu.html(树形菜单网页名称固定)

1、实现页面基本效果

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <ul>
    <li>树形菜单开发
      <ul>
        <li>实现基本网页</li>
        <li>JS获取页面标签</li>
        <li>实现菜单点击</li>
        <li>实现菜单显示切换</li>
      </ul>
    </li>
    <li>
      选项卡效果
      <ul>
        <li>实现基本网页</li>
        <li>js获取页面标签</li>
        <li>标题事件添加</li>
        <li>标题样式切换</li>
        <li>内容展示切换</li>
      </ul>
    </li>
    <li>自定义右键菜单</li>
    <li>倒计时</li>
    <li>数字时钟</li>
  </ul>
</body>
</html>

2、js获取页面标签

<script>
  // 等网页内容加载完成,执行树形菜单效果
  window.onload = function() {

    // 声明树形菜单函数
    function treeMenu() {
      // 获取页面标签
      var _lis = document.getElementsByTagName("li")

      // ...
      }

    // 调用执行
    treeMenu()

  }
</script>

3、标签对象点击事件

给获取的菜单标签,循环添加单击事件,让菜单可以点击

// 声明树形菜单函数
      function treeMenu() {
        // 获取页面标签
        var _lis = document.getElementsByTagName("li")
        console.log(_lis, typeof(_lis))
        // --------------------------- 添加 >>>>>>>>>>
        // 循环遍历所有li菜单
        for(var index in _lis) {
          // 获取当前菜单标签
          var menu = _lis[index]

          // 添加单击事件
          menu.onclick = function() {
            alert("用户点击了菜单")
          }
        //----------------------------------<<<<<<<<<<<<<
        }
      }

4、子菜单显示或者隐藏

点击菜单选项,如果没有子菜单就什么都不做;如果包含子菜单~让子菜单显示/隐藏切换

事件循环的代码中,添加子菜单显示/隐藏 切换功能:

// 循环遍历所有li菜单
for(var index in _lis) {
  // 获取当前菜单标签
  var menu = _lis[index]

  // 添加单击事件
  menu.onclick = function() {
    // ------------------------------------添加 >>>>>>>>>>>>>>>>>
    // 获取子菜单
    var children = this.children
    if(children.length > 0) {
      // 存在子菜单,获取唯一的子菜单
      var child = children[0]
      // 判断行内样式
      if(child.style.display === "block") {
        child.style.display = "none"
      } else {
        child.style.display = "block"
      }
    }
	// --------------------------------------<<<<<<<<<<<<<<<<<<<<<<<<
  }

5、完善树形菜单

树形菜单中,一旦包含三级菜单,事件冒泡影响了树形菜单的显示和隐藏效果

<ul>
    <li>树形菜单开发
      <ul style="display: block">
        <li>实现基本网页</li>
        <li>JS获取页面标签</li>
        <li>实现菜单点击</li>
        <li>实现菜单显示切换
          <ul>
            <li>获取当前菜单子菜单</li>
            <li>判断是否包含子菜单</li>
            <li>不包含:什么都不做</li>
            <li>包含:判断样式,显示/隐藏切换</li>
          </ul>
        </li>
      </ul>
    </li>
    <li>
      选项卡效果
      <ul style="display: block"> 
        <li>实现基本网页</li>
        <li>js获取页面标签</li>
        <li>标题事件添加</li>
        <li>标题样式切换</li>
        <li>内容展示切换</li>
      </ul>
    </li>
    <li>自定义右键菜单</li>
    <li>倒计时</li>
    <li>数字时钟</li>
  </ul>

完善js代码,添加阻止事件冒泡的处理

// 添加单击事件
menu.onclick = function(e) {
  // 获取事件对象
  var e = e || window.event
  e.stopPropagation ? e.stopPropagation():e.cancelBubble = true
    ......

二、选项卡

1、实现页面基本效果

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    *{margin: 0; padding: 0; box-sizing: border-box;}
    #box{width: 400px;height:300px; margin: 50px auto;border-radius: 5px; border:solid 2px #888; overflow:hidden;}
    #title{height:50px; display: flex; border-bottom: solid 2px orangered;}
    #title span{cursor: pointer;flex: 1; display: block; text-align:center; line-height: 50px;}
    #title span.active {background: orangered; color: white;}
    #content{position: relative}
    #content p{position: absolute; top: 10px; left: 10px; opacity: 0;}
    #content p.active{opacity: 1;}
  </style>
</head>
<body>
  <div id="box">
    <div id="title">
      <span class="active">新闻</span>
      <span>通告</span>
      <span>动态</span>
    </div>
    <div id="content">
      <p class="active">新闻内容</p>
      <p>通告内容</p>
      <p>动态内容</p>
    </div>
  </div>
</body>
</html>

2、js获取需要的标签

第一步先获取需要的各种标签对象

<script>
  window.onload = function() {

    // 封装tab选项卡效果函数
    function tab() {

      // 获取需要的标签
      var _spans = document.getElementsByTagName("span")
      var _ps = document.getElementsByTagName("p")

    }


    tab()

  }
</script>

3、添加标题单击事件

给获取到的选项卡标题对象,添加单击事件,让标题可以点击

// 封装tab选项卡效果函数
function tab() {

  // 获取需要的标签
  var _spans = document.getElementsByTagName("span")
  var _ps = document.getElementsByTagName("p")

  //  --------------------------------------------- 添加>>>>>>>>>>>>>
  // 给标题添加点击操作
  for(var i = 0; i < _spans.length; i++) {
    // 记录当前标题的索引:使用自定义属性记录索引
    _spans[i].index = i
    // 点击事件
    _spans[i].onclick = function() {
      alert("标题被点击了: " + this.index)
    }
  }
  // ---------------------------------------------<<<<<<<<<<<<<<<<<<<<<

}

4、修改标题样式

当前标题被点击之后,修改样式class="active",用户点击之后就会得到一个样式反馈,知道那个标题被点击了

// 给标题添加点击操作
for(var i = 0; i < _spans.length; i++) {
  // 记录当前标题的索引:使用自定义属性记录索引
  _spans[i].index = i
  // 点击事件
  _spans[i].onclick = function() {
		// --------------------------------------添加>>>>>>>>>>>>>>>>>>>>>>>
    // 删除所有标题的class="active"样式
    for(var j = 0; j < _spans.length; j++){
      // 修改span标签的class属性
      _spans[j].className = ""
    }
    // 给当前被点击的标题,添加class="active"
    this.className = "active" 
		// ----------------------------------<<<<<<<<<<<<<<<<<<<<<<<<
  }
}

5、修改内容显示

选项卡标题发生点击和改变时,让对应的内容显示出来

// 给标题添加点击操作
for(var i = 0; i < _spans.length; i++) {
  // 记录当前标题的索引:使用自定义属性记录索引
  _spans[i].index = i
  // 点击事件
  _spans[i].onclick = function() {

    // 删除所有标题的class="active"样式
    for(var j = 0; j < _spans.length; j++){
      // 修改span标签的class属性
      _spans[j].className = ""
    }
    // 给当前被点击的标题,添加class="active"
    this.className = "active" 
		// -------------------------------------------------- 添加>>>>>>>>>>>>>>>
    // 让所有的内容隐藏
    for(var z = 0; z < _ps.length; z++){
      _ps[z].className = ""
    }
    // 让对应的内容显示
    _ps[this.index].className = "active"
    // -------------------------------------------<<<<<<<<<<<<<<<<<<<<<<<<<<<
  }
}

三、自定义右键菜单

1、实现基本网页效果

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    *{margin: 0; padding: 0; box-sizing: border-box;}
    #menu{position: absolute; opacity: 0; width:0px;height:0px;box-shadow: #000 0 0 3px;list-style: none; display: flex; flex-direction: column; justify-content: space-between;}
    #menu li{height: 50px; line-height: 50px; cursor:pointer; text-align: center;}
    #menu li:hover{background:#555; color: white;}

  </style>
</head>
<body>
  <ul id="menu">
    <li>自定义菜单</li>
    <li>自定义菜单</li>
    <li>自定义菜单</li>
    <li>自定义菜单</li>
  </ul>
</body>
</html>

2、阻止默认右键菜单

通过网页文档的事件对象,阻止浏览器默认右键菜单

<script>
  window.onload = function() {
    // 添加鼠标右键在网页中点击的事件
    document.oncontextmenu = function(e) {
      // 阻止默认行为:阻止右键菜单
      var e = e || window.event
      e.preventDefault ? e.preventDefault() : e.returnValue = false
    }
  }
</script>

3、显示自定义右键菜单

点击鼠标右键的位置,显示自定义右键菜单:

window.onload = function() {

      var _menu = document.getElementById("menu")

      
      // 添加鼠标右键在网页中点击的事件
      document.oncontextmenu = function(e) {
        // 阻止默认行为:阻止右键菜单
        var e = e || window.event
        e.preventDefault ? e.preventDefault() : e.returnValue = false

        // ---------------------------------------------添加:菜单显示<<<<<<<<<<
        // 显示右键菜单:鼠标在浏览器窗口中的位置显示菜单
        _menu.style.left = e.clientX + "px"
        _menu.style.top = e.clientY + "px"
        _menu.style.opacity = 1
        _menu.style.height = "200px"
        _menu.style.width = "200px"
      }

      // -------------------------------------------添加:菜单隐藏
      // 网页中任意位置点击鼠标左键,让菜单消失
      document.onclick = function() {
        _menu.style.opacity = 0
        _menu.style.height = "0px"
        _menu.style.width = "0px"
      }
    }

4、提升用户体验

让自定义右键菜单,呈现动画效果,通过样式进行处理

  <style>
    *{margin: 0; padding: 0; box-sizing: border-box;}
    #menu{overflow:hidden;transition-property:width,height; transition-duration:.2s;position: absolute; opacity: 0; width:0px;height:0px;box-shadow: #000 0 0 3px;list-style: none; display: flex; flex-direction: column; justify-content: space-between;}
    #menu li{height: 50px; line-height: 50px; cursor:pointer; text-align: center;}
    #menu li:hover{background:#555; color: white;}
  </style>

四、数字时钟

1、实现网页基本样式

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #clock{font-size:120px;}
  </style>
</head>
<body>
  <div id="clock">0000-00-00 00:00:00</div>
</body>
</html>

2、添加计时函数实现数字时钟

网页打开或者刷新的时候,展示动态数字时钟

<script>
  window.onload = function() {

    // 获取当前时间的函数
    function getTime() {
      var date = new Date()
      return date.getFullYear() + "-"
        + (date.getMonth() + 1).toString().padStart(2, "0") + "-"
        + date.getDate().toString().padStart(2, "0") + " "
        + date.getHours().toString().padStart(2, "0") + ":"
        + date.getMinutes().toString().padStart(2, "0")+":"
        + date.getSeconds().toString().padStart(2, "0")
    }

    // 数字时钟
    var _clock = document.getElementById("clock")
    !function() {
      setInterval(function() {
        var result = getTime()
        _clock.innerText = result
      }, 1000)
    }();

  }
</script>

五、倒计时

1、实现页面基本效果

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #countdown{font-size:100px;}
  </style>
</head>
<body>
  <h2>距离国庆还有:</h2>
  <div id="countdown">
    XX天 XX时 XX分 XX秒 XXX
  </div>
</body>
</html>

2、获取并计算时间差

编写JavaScript代码,实现获取当前时间到目标时间的时间差

<script>

    window.onload = function() {

      // 倒计时函数
      function countDownFn() {
        // 获取当前时间
        var date = new Date()
        // 获取国庆时间
        var tgt = new Date('2022-10-01 00:00:00')
        // 获取时间差
        var distance = tgt - date
        if(distance <= 0) {
          alert("目标时间不能小于当前时间")
          return
        }
        console.log(distance, "时间差")
      }

      countDownFn()
    }


  </script>

3、计算时间差对应的天数/小时/分钟…

<script>

  window.onload = function() {

    var _countdown = document.getElementById("countdown")
    var _time;

    // 倒计时函数
    function countDownFn() {
      // 获取当前时间
      var date = new Date()
      // 获取国庆时间
      var tgt = new Date('2022-10-01 00:00:00')
      // 获取时间差
      var distance = tgt - date
      if(distance <= 0) {
        alert("目标时间不能小于当前时间")
        clearInterval(_time)
        return
      }
      console.log(distance, "时间差")

      // 计算剩余时间
      var d = Math.floor(distance / (1000 * 60 * 60 * 24))
      var h = Math.floor(distance / (1000 * 60 * 60) % 24) 
      var m = Math.floor(distance / (1000 * 60) % 60)
      var ms= distance % 1000

      var time = d.toString().padStart(2, "0") + "天" 
      + h.toString().padStart(2, "0") + "时" 
      + m.toString().padStart(2, "0") + "分" 
      + ms.toString().padStart(3, "0")

      _countdown.innerText = time
    }

    _time = setInterval(function() {
      countDownFn()
    }, 80)
  }


</script>

六、模拟时钟

1、实现网页基本效果

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #clock{
      margin: 50px auto;
      width: 300px;
      height: 400px;
      background-image: url('./images/bp.webp');
      background-size: 300px 400px;
      position: relative;
    }
    #s{
      width:2px;
      height:110px;
      background-color:orangered;
      position: absolute;
      top: 65px;
      left: 154px;
    }
    #m{
      width:4px;
      height:80px;
      background-color:blue;
      position: absolute;
      top: 95px;
      left: 153px;
    }
    #h{
      width:6px;
      height:60px;
      background-color:rgb(19, 222, 32);
      position: absolute;
      top: 115px;
      left: 152px;
    }

  </style>
</head>
<body>
  <div id="clock">
    <div id="s"></div>
    <div id="m"></div>
    <div id="h"></div>
  </div>
</body>
</html>

2、获取页面中需要的各种标签

获取要操作的时针、分针、秒针标签对象,分别使用三个变量记录对应的小时、分钟、秒钟

 <script>
   window.onload = function() {

     // 获取标签对象
     var _s = document.getElementById("s")
     var _m = document.getElementById("m")
     var _h = document.getElementById("h")

     // 声明变量,记录时间
     var sVal = 0   // 0~59
     var mVal = 0   // 0~59
     var hVal = 0   // 0~23

     }
</script>

3、秒针转动

 // 计时函数:1秒执行一次
setInterval(function() {
  // 秒钟增加,一旦超过60秒,会到0
  sVal ++
  if(sVal >= 60) {
    sVal = 0
  }

  // 秒针转动
  _s.style.transform = "rotate(" + (sVal * 6) + "deg)"

}, 1000)

4、分针转动

思考:分针如何转动?秒钟转一圈,分针转一格(6dep

// 计时函数:1秒执行一次
      setInterval(function () {
        // 秒钟增加,一旦超过60秒,会到0
        sVal++
        if (sVal >= 60) {
          sVal = 0
          // --------------------------------- 添加
          // 秒钟转一圈,分针加1
          mVal++
          if (mVal >= 60) {
            mVal = 0
          }
          // -----------------------------------
        }


        // 秒针转动
        _s.style.transform = "rotate(" + (sVal * 6) + "deg)"

        // --------------------------------- 添加
        // 分针转动
        _m.style.transform = "rotate(" + (mVal * 6) + "deg)"

        // ------------------------------------
      }, 1000)

5、时针转动

模仿分针转动,实现最终效果

<script>
  window.onload = function () {

    // 获取标签对象
    var _s = document.getElementById("s")
    var _m = document.getElementById("m")
    var _h = document.getElementById("h")

    // 声明变量,记录时间
    var sVal = 0   // 0~59
    var mVal = 0   // 0~59
    var hVal = 0   // 0~23

    // 计时函数:1秒执行一次
    setInterval(function () {
      // 秒钟增加,一旦超过60秒,会到0
      sVal++
      if (sVal >= 60) {
        sVal = 0
        // 秒钟转一圈,分针加1
        mVal++
        if (mVal >= 60) {
          mVal = 0

          // 分针转一圈,时针+1
          hVal ++
          if(hVal >= 23){
            hVal = 0
          }
        }
      }


      // 秒针转动
      _s.style.transform = "rotate(" + (sVal * 6) + "deg)"

      // 分针转动
      _m.style.transform = "rotate(" + (mVal * 6) + "deg)"

      // 时针转动
      _h.style.transform = "rotate(" + (hVal * 6) + "deg)"
    }, 1000)

  }
</script>

6、系统时间同步

思考:sVal、mVal、hVal怎么和系统时间同步?

<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #clock {
      margin: 50px auto;
      width: 400px;
      height: 400px;
      background-image: url('./images/bg.png');
      background-size: 400px 400px;
      position: relative;
    }

    #s {
      transform-origin: 0px 189px;
      width: 2px;
      height: 190px;
      background-color: orangered;
      position: absolute;
      top: 10px;
      left: 199px;
    }

    #m {
      /* display: none; */
      transform-origin: 0px 140px;
      width: 4px;
      height: 140px;
      background-color: blue;
      position: absolute;
      top: 63px;
      left: 198px;
    }

    #h {
      transform-origin: 0px 120px;
      width: 6px;
      height: 120px;
      background-color: rgb(19, 222, 32);
      position: absolute;
      top: 83px;
      left: 197px;
    }
  </style>
</head>

<body>
  <div id="clock">
    <div id="s"></div>
    <div id="m"></div>
    <div id="h"></div>
  </div>

  <script>
    window.onload = function () {

      // 获取标签对象
      var _s = document.getElementById("s")
      var _m = document.getElementById("m")
      var _h = document.getElementById("h")

      // 声明变量,记录时间
      var sVal = 0   // 0~59
      var mVal = 0   // 0~59
      var hVal = 0   // 0~23

      // 系统时间同步
      var date = new Date()
      sVal = date.getSeconds()
      mVal = date.getMinutes()
      hVal = date.getHours()
      console.log(hVal)

      // 计时函数:1秒执行一次
      setInterval(function () {
        // 秒钟增加,一旦超过60秒,会到0
        sVal++
        if (sVal >= 60) {
          sVal = 0
          // 秒钟转一圈,分针加1
          mVal++
          if (mVal >= 60) {
            mVal = 0

            // 分针转10圈,时针+1
            hVal ++
            if(hVal >= 23){
              hVal = 0
            }
          }
        }


        // 秒针转动
        _s.style.transform = "rotate(" + (sVal * 6) + "deg)"

        // 分针转动
        _m.style.transform = "rotate(" + (mVal * 6) + "deg)"

        // 时针转动
        _h.style.transform = "rotate(" + (hVal * 30 + mVal * 0.5) + "deg)"
      }, 1000)

    }
  </script>
</body>

</html>

七、拖拽效果

1、网页基础效果

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #box{width:300px;height:200px;background:orangered;position:absolute;}
  </style>
</head>
<body>
  <div id="box"></div>
</body>
</html>

2、拖拽原理

鼠标拖动一个div移动

定义鼠标的位置:让div的样式top / left跟着鼠标位置移动

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-m6QSvWz8-1660442947668)(assets/image-20220812141707307.png)]

3、实现拖拽

通过JavaScript实现鼠标拖拽

<script>

  window.onload = function() {

    var _box = document.getElementById("box")

    // 鼠标单击
    _box.onmousedown = function(e) {
      // 获取offsetX、offsetY(鼠标在div上的位置)
      var e = e || window.event
      var offsetX = e.offsetX
      var offsetY = e.offsetY

      // 鼠标在document上移动
      document.onmousemove = function(event) {
        // 获取鼠标在浏览器窗口中的位置
        var event = event || window.event
        var clientX = event.clientX
        var clientY = event.clientY

        // div定位
        _box.style.left = clientX - offsetX + "px"
        _box.style.top = clientY - offsetY + "px"
      }
    }

    // 鼠标抬起:鼠标的移动事件消失/取消
    document.onmouseup = function() {
      document.onmousemove = null
    }

  }

</script>

八、科学计算器

1、网页基本效果

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    *{margin: 0; padding: 0; box-sizing: border-box;}
    html, body{
      background:aliceblue;
    }
    #calculate{
      background: white;
      width: 300px;
      height: 500px;
      border-radius: 8px;
      box-shadow: #000 0 0 3px;
      margin: 50px auto;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    #show{
      height: 50px;
      width:260px;
      padding: 10px;
      text-align: right;
      border: solid 3px #aaa;
      border-radius: 2px;
      overflow:hidden;
      font-size: 22px;
      margin: 40px 0 20px 0;
    }
    #board{
      height: 340px;
      width: 260px;
      overflow: hidden;
      display: flex;
      justify-content: space-around;
      flex-wrap: wrap;
    }
    #board p{
      cursor: pointer;
      margin-bottom:10px;
      width: 60px;
      height: 60px;
      border-radius: 5px;
      background-color:#f1f1f1;
      text-align:center;
      font-size: 18px;
      font-weight: bolder;
      line-height: 60px;
    }
    #board p:hover{
      background:#333;
      color: white;
    }
  </style>
</head>
<body>
  <div id="calculate">
    <div id="show">
      0
    </div>
    <div id="board">
      <p>sin</p>
      <p>cos</p>
      <p>tan</p>
      <p>+</p>
      <p>7</p>
      <p>8</p>
      <p>9</p>
      <p>-</p>
      <p>4</p>
      <p>5</p>
      <p>6</p>
      <p>*</p>
      <p>1</p>
      <p>2</p>
      <p>3</p>
      <p>/</p>
      <p>CE</p>
      <p>0</p>
      <p>.</p>
      <p>=</p>
    </div>
  </div>
</body>
</html>

2、js获取页面标签

将网页中用户可以点击的按钮标签,全部获取出来

<script>
  window.onload = function() {

    // 获取页面中需要操作的标签
    var _ps = document.getElementsByTagName("p")

    // 循环添加点击事件
    for(var i = 0; i < _ps.length; i++) {

      _ps[i].onclick = function() {
        alert("用户点击了" + this.innerText)
      }
    }

  }
</script>

3、处理用户输入

用户可以点击计算器按钮,用户点击数字、操作符号时,建议拼接字符串输出

用户点击CE时,清除数据,显示0

用户点击=时,计算表达式,显示结果数据

// 循环添加点击事件
for(var i = 0; i < _ps.length; i++) {

  // 拼接输出的数据
  var showValue = ""

  _ps[i].onclick = function() {

    // 获取用户点击的数据
    var _val = this.innerText

    // 判断并输出
    switch(_val) {
      case "1":
      case "2":
      case "3":
      case "4":
      case "5":
      case "6":
      case "7":
      case "8":
      case "9":
      case "0":
      case "+":
      case "-":
      case "*":
      case "/":
        // 拼接输出数据
        if(showValue.startsWith("0")){
          showValue = _val
        } else {
          showValue += _val
        }
        break
      case "CE":
        showValue = "0"
        break
      case "sin":
      case "cos":
      case "tan":
        // 三角函数
        break
      case "=":
        // 计算结果
        break
    }

    _show.innerText = showValue
  }
}

4、处理基本运算

JavaScript中提供了一个特殊函数:eval()

作用:将一个字符串类型的表达式,转化成可执行的脚本代码

var s = "12 + 12"
var res = eval(s)   // eval("12 + 12") -> 12 + 12
console.log(res) // 24

var s = "12 + 12 -"
var res = eval(s)   // eval("12 + 12") -> 12 + 12 -
console.log(res) // Uncaught SyntaxError

解决字符串拼接的表达式的运算:使用eval()进行转换即可

...
case "=":
  // 计算结果
  showValue = eval(showValue)
  break
...

5、处理科学运算

// 判断并输出
switch(_val) {
  case "1":
  case "2":
  case "3":
  case "4":
  case "5":
  case "6":
  case "7":
  case "8":
  case "9":
  case "0":
  case "+":
  case "-":
  case "*":
  case "/":
    // 拼接输出数据
    if(showValue.startsWith("0") && !showValue.startsWith("0.")){
      showValue = _val
    } else {
      showValue += _val
    }
    break
  case "DEL":
    if(showValue !== "0" && showValue.length > 1) {
      showValue = showValue.substr(0, showValue.length-1)
    }  
    break;
  case ".":
    //   if(!showValue.includes(".")){
    //     showValue += "."
    //   }
    alert("暂不支持浮点数运算")
    break
  case "CE":
    showValue = "0"
    break
  case "sin":
    showValue = Math.sin(parseFloat(showValue))
    break
  case "cos":
    showValue = Math.cos(parseFloat(showValue))
    break
  case "tan":
    // 三角函数
    showValue = Math.tan(parseFloat(showValue))
    break
  case "=":
    // 计算结果
    showValue = eval(showValue)
    break
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值