<!DOCTYPE html>
<html lang="en">
<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>Vue.js 鼠标移动监听与动态背景色改变</title>
  <script src="vue.js"></script>
  <style>
    #app > div {
      width: 128px;
      height: 128px;
    }
  </style>
</head>
<body>
  <div id="app">
    <p>鼠标位于({{ x }}, {{ y }})</p>
    <p>背景色{{ backgroundColor }}</p>
    <div v-on:mousemove="mouseMove" v-bind:style="{ backgroundColor }">
    </div>
  </div>
  <script>
    let vm = new Vue({
      el: "#app",
      data: { x: 0, y: 0 },
      methods: {
        mouseMove(event) {
          this.x = event.offsetX;
          this.y = event.offsetY;
        }
      },
      computed: {
        backgroundColor() {
          const c = (this.x + this.y).toString(16);
          return c.length == 2
            ? `#${c}${c}${c}`
            : `#0${c}0${c}0${c}`;
        }
      }
    });
  </script>
</body>
</html>
<p>浏览器加载HTML文件 -&gt; 解析HTML结构 -&gt; 加载Vue.js -&gt; 解析Vue实例 -&gt; 将数据和方法绑定到DOM上 -&gt; 监听鼠标移动事件 -&gt; 根据鼠标位置计算背景色 -&gt; 更新背景色和鼠标位置的数据 -&gt; 将更新后的数据渲染到DOM上 -&gt; 用户在浏览器中看到输出结果。</p>

原文地址: https://www.cveoy.top/t/topic/on2S 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录