当前位置:首页 > 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实现日历

实现日历的基本思路 使用JavaScript实现日历的核心是动态生成日期表格,并处理月份切换逻辑。需要计算当前月的天数、起始星期几,并动态渲染到页面上。 获取当前日期信息 通过Date对象获取当前年…

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('image…

js防抖和节流实现

js防抖和节流实现

防抖(Debounce)的实现 防抖的核心思想是在事件被触发后,延迟执行回调函数。如果在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口大小调整等场景。 function debounce…

js实现报表

js实现报表

使用JavaScript实现报表 在JavaScript中实现报表功能可以通过多种方式完成,常见的方法包括使用原生JavaScript、第三方库(如Chart.js、D3.js)或结合后端数据渲染。以…

js实现百叶窗

js实现百叶窗

使用CSS和JavaScript实现百叶窗效果 通过CSS动画和JavaScript事件监听可以实现百叶窗效果。核心思路是将内容区域分割为多个条状元素,通过控制它们的展开/折叠状态来模拟百叶窗。 &…

js类实现

js类实现

使用类实现 JavaScript 功能 在 JavaScript 中,类(Class)是一种语法糖,基于原型继承机制。通过 class 关键字可以更直观地定义对象模板。 基本类定义 class…