当前位置:首页 > JavaScript

js实现方块

2026-03-14 11:41:20JavaScript

使用HTML和CSS创建方块

在HTML中创建一个方块可以通过<div>元素结合CSS样式实现。以下是一个简单的示例:

<div class="square"></div>
.square {
  width: 100px;
  height: 100px;
  background-color: blue;
}

使用JavaScript动态生成方块

通过JavaScript动态创建方块并添加到DOM中:

// 创建方块元素
const square = document.createElement('div');
square.style.width = '100px';
square.style.height = '100px';
square.style.backgroundColor = 'red';

// 添加到页面
document.body.appendChild(square);

实现可交互的方块

添加事件监听器使方块可点击或可拖动:

const square = document.createElement('div');
square.style.width = '100px';
square.style.height = '100px';
square.style.backgroundColor = 'green';
square.style.cursor = 'pointer';

// 点击改变颜色
square.addEventListener('click', () => {
  square.style.backgroundColor = 'yellow';
});

document.body.appendChild(square);

使用Canvas绘制方块

通过Canvas API绘制方块:

<canvas id="canvas" width="200" height="200"></canvas>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// 绘制红色方块
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);

方块动画效果

使用JavaScript实现方块移动动画:

const square = document.createElement('div');
square.style.width = '50px';
square.style.height = '50px';
square.style.backgroundColor = 'purple';
square.style.position = 'absolute';
document.body.appendChild(square);

let pos = 0;
function animate() {
  pos++;
  square.style.left = pos + 'px';
  if (pos < 200) {
    requestAnimationFrame(animate);
  }
}
animate();

响应式方块

创建随窗口大小变化的方块:

js实现方块

const square = document.createElement('div');
square.style.width = '20vw';
square.style.height = '20vw';
square.style.backgroundColor = 'orange';
document.body.appendChild(square);

标签: 方块js
分享给朋友:

相关文章

js实现继承

js实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js实现变形

js实现变形

使用 CSS 和 JavaScript 实现元素变形 在 JavaScript 中实现变形效果通常结合 CSS 的 transform 属性,通过动态修改该属性实现元素的旋转、缩放、倾斜或平移。 基…

js实现目录

js实现目录

实现目录的基本思路 在JavaScript中实现目录功能通常涉及以下几个核心步骤:解析文档中的标题元素(如h1-h6),动态生成目录结构,并添加交互逻辑(如点击跳转)。以下是具体实现方法: 解析标题…

节流js实现

节流js实现

节流(Throttle)的实现原理 节流是一种限制函数执行频率的技术,确保函数在一定时间间隔内最多执行一次。适用于高频触发事件(如滚动、输入、窗口调整等)的场景。 基础实现方式 使用时间戳判断是否执…

js实现删除

js实现删除

使用 splice 方法删除数组元素 splice 方法可以删除数组中的元素,并返回被删除的元素。它接受两个参数:起始索引和要删除的元素数量。 const array = [1, 2, 3, 4…

js 实现日历

js 实现日历

实现日历的基本思路 日历的核心功能是展示日期,并允许用户进行日期选择或导航。JavaScript 可以动态生成日历的 HTML 结构,并处理用户交互逻辑。 基础日历结构 日历通常包含头部(显示月份和…