我正在尝试制作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>
有人可以帮助我吗?
答案 0 :(得分:2)
您是否想要这样的行为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";
}
答案 1 :(得分:1)
let delayInSecond = 100; //100 millisecond
let squireElem = document.querySelector('.squire');
let maxHeight = window.innerHeight;
let posTop = 50;
let posRight = 0;
let posBottom = 0;
let posLeft = 0;
let correction=50;
squireElem.style.top="50px";
let timer = setInterval(squire, delayInSecond);
let maxWidth=window.innerWidth;
function squire() {
let elemHeight = parseInt(squireElem.style.top);
if( elemHeight<maxHeight-correction&&posLeft<=correction) {
posTop += 10;
squireElem.style.top = posTop + 'px';
}
else if(elemHeight>=maxHeight-correction&&posLeft<maxWidth-correction) {
posLeft+= 10;
squireElem.style.left = posLeft + 'px';
}
else if(elemHeight <=maxHeight-correction&&posLeft>=maxWidth-correction&&posTop>50) {
posTop -= 10;
squireElem.style.top = posTop + 'px';
}
else if(posTop<=correction&&posLeft>=correction) {
posLeft -= 10;
squireElem.style.left = posLeft + 'px';
}
else{ }
}