首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用javascript上、下、左、右移动方框

使用javascript上、下、左、右移动方框
EN

Stack Overflow用户
提问于 2019-11-17 22:24:42
回答 2查看 3.4K关注 0票数 1

所以我想让长方体在所有方向上移动,方法是将长方体相乘,然后去掉下半部分。Up和right起作用,但down和left不起作用。函数在4个按钮中的1个点击时被调用。基本的CSS和html。我该怎么解决这个问题?

代码语言:javascript
运行
复制
var box = document.getElementById("box");
var container = document.getElementById("container");
var time = document.getElementById("time");
let up2 = 1;
let right2 = 1;
let left2 = 1;
let down2 = 1;

function up() {
  box.style.height = 30 + "px";
  box.style.bottom = 30 * up2 + "px";
  up2++;
}

function right() {
  box.style.right = 30 + "px";
  box.style.left = 30 * right2 + "px";
  right2++;
}

function left() {
  box.style.left = 30 + "px";
  box.style.right = 30 * left2 + "px";
  left2++;
}

function down() {
  box.style.bottom = 30 + "px";
  box.style.top = 30 * down2 + "px";
  down2++;
}
代码语言:javascript
运行
复制
#container {
  position: relative;
  background: purple;
  width: 400px;
  height: 400px;
}

#box {
  position: absolute;
  background: red;
  width: 30px;
  height: 30px;
  bottom: 0px;
}
代码语言:javascript
运行
复制
<div id="container">
  <div id="box"></div>
</div>

<br />
<button class="up" onclick="up()">↑</button>

<br />

<button class="right" onclick="left()">←</button>

<button class="left" onclick="right()">→</button>

<br />

<button class="down" onclick="down()">↓</button>

EN

Stack Overflow用户

发布于 2019-11-18 01:09:25

这里你可以看到另一个例子..

代码语言:javascript
运行
复制
class box{
 constructor() {  
   this.box = document.getElementById("box");
   this.container = document.getElementById("container");
   this.y = 1;
   this.x = 1;
 }
draw(){
  this.box.style.top = this.y + "px";
  this.box.style.left = this.x + "px";
}
up() {
  this.y += -30;
  this.draw()
}
 right() {
 this.x += 30;
    this.draw()
}
 left() {
   this.x += -30;
    this.draw()
 
}
  down() {
    this.y += 30;  
     this.draw()
  }
}

 var box2 = new box();


box2.draw()
代码语言:javascript
运行
复制
#container {
  position: relative;
  background: purple;
  width: 400px;
  height: 400px;
}

#box {
  position: absolute;
  background: red;
  width: 30px;
  height: 30px;
  bottom: 0px;
}
代码语言:javascript
运行
复制
  <div id="container">
  <div id="box"></div>
</div>

<br />
<button class="up" onclick="box2.up.call(box2)">↑</button>

<br />

<button class="right" onclick="box2.left.call(box2)">←</button>

<button class="left" onclick="box2.right.call(box2)">→</button>

<br />

<button class="down" onclick="box2.down.call(box2)">↓</button>

票数 2
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58901429

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档