javascript - 如何改变一个简单拼图的方向

标签 javascript

我正在尝试制作 this sample puzzle .我想改变方向,如果拼图触摸底部窗口,那么它会像以前一样沿着右侧窗口转动,然后在触摸右侧窗口后再次移动到顶部窗口

let delayInSecond = 1000; //1 second
let squireElem = document.querySelector('.squire');
let maxHeight = window.innerHeight;
let posTop = 50;
let posRight = 0;
let posBottom = 0;
let posLeft = 0;

let timer = setInterval(squire, delayInSecond);

function squire() {
  let elemHeight = squireElem.offsetHeight;
  if (maxHeight === elemHeight) {
    clearInterval(timer);
  } else {
    posTop += 10;
    posRight += 10;
    posBottom += 10;
    posLeft += 10;
    squireElem.style.top = posTop + 'px';
    squireElem.style.left = posLeft + 'px';
  }
}
* {
  margin: 0;
  padding: 0;
}

.squire {
  width: 100px;
  height: 100px;
  background-color: blue;
  position: absolute;
  top: 50px;
}
<div class="squire"></div>

谁能帮帮我?

最佳答案

你想要这样的行为吗https://codepen.io/benrampon/pen/eoRaVE

let delayInSecond = 100;
let squireElem = document.querySelector(".squire");
let windowHeight = window.innerHeight;
let windowWidth = window.innerWidth;
let posTop = 50;
let posRight = 0;
let posBottom = 0;
let posLeft = 0;
let goToRight = true
let goToBottom = true

let timer = setInterval(squire, delayInSecond);
function maxStep(max,range) {
  return max <= range ? max : range
}
function squire() {
  let elemBottomPosition = squireElem.offsetTop + squireElem.offsetHeight;
  let elemTopPosition = squireElem.offsetTop;
  let elemRightPosition = squireElem.offsetLeft + squireElem.offsetWidth;
  let elemLeftPosition = squireElem.offsetLeft;
  if(elemLeftPosition<=0){
    goToRight = true
  }else if(elemRightPosition>= windowWidth){
    goToRight = false    
  }
  if(elemTopPosition<=0){
    goToBottom = true
  }else if(elemBottomPosition>= windowHeight){
    goToBottom = false    
  } 
  const stepWidth = goToRight ? maxStep(10,windowWidth-elemRightPosition) : maxStep(10,elemLeftPosition)
  const stepHeight = goToBottom ? maxStep(10,windowHeight-elemBottomPosition) : maxStep(10,elemTopPosition)
  posTop = goToBottom ? posTop+stepHeight : posTop-stepHeight;
  posLeft = goToRight ? posLeft + stepWidth : posLeft-stepWidth;
  squireElem.style.top = posTop + "px";
  squireElem.style.left = posLeft + "px";
}

关于javascript - 如何改变一个简单拼图的方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55653801/

相关文章:

javascript - 如何在 React 中的 setState 对象数组上添加项目?

javascript - 编辑类型为 number 的输入标签,并且 onInputChange 仅在按下 Enter 时执行

javascript - 如何在 HTML 属性内的函数调用中将变量作为参数传递?

javascript - 使用 jQuery 的 .on() 方法防止 Ajax.BeginForm 中提交的默认行为

javascript - 比较 Vanilla JS 中包含对象的两个数组

javascript - 单击链接时如何选择同级元素?

javascript - 如何确定选择已被清除

javascript - jquery传递单选按钮数组

javascript - 找不到模块 : Error: Package path ./locales 在 Angular 更新到 13 后未从包中导出

JavaScript:Jasmine 错误:预期 { 0 : HTMLNode, length : 1 } 为 '#containers'