Проблемы с синтаксисом:
style.transform
не имеет дополнительных свойств (x и y).
Вам придется проанализировать его самостоятельно, используя разделение или регулярное выражение.
- Отсутствует
px
в части перевода y, что делает его недействительным
wordStore.style.transform = "translate(" + velocity + "px ," + velocity + "px)";
- Условие привязки logi c
(x < y < z)
не действует в javascript
x < y && y < z
Логические проблемы:
- С вашим текущим logi c, кнопки будут отскакивать назад по той же предопределенной линии
- Как только кнопки выйдут за пределы, ваши движения остановятся, так как вы никогда не добавляете никакого значения к фактическому положению после реверсирования
velocity
- Вы могли бы использовать
class
как id
, что нормально, но глупо
Пример с комментариями на основе вашего кода:
Примечание. полностраничный режим
var upperVelocity = 10;
var lowerVelocity = 2;
//var velocity = 5; //REM: Dropped to bring some random dynamic into it
var speed = 25; //REM: Interval-Timeout
var bounds = null;
//REM: Calculating the bounds according to the bounds of .wordGameContainer
//var upperLimitY = 360;
//var lowerLimitY = 0;
//var upperLimitX = 520;
//var lowerLimitX = 0;
//REM: Not required, since there is only one "word1"
//var wordStore = document.getElementsByClassName("word1")[0];
function startGame(){
//REM: Calculating the bounds
bounds = document.querySelector(".wordGameContainer").getBoundingClientRect();
//REM: Getting all .words
var tListOfWords = document.getElementsByClassName("word");
for(var i=0, j=tListOfWords.length; i<j; i++){
//REM: Clearing the current timeout, else speeds up on pressing again
clearInterval(tListOfWords[i].dataset.Interval);
//REM: x and y require different directions, else they just keep bouncing back and forth diagonally
tListOfWords[i].dataset.Direction = JSON.stringify({x: 1, y: 1});
//REM: Storing the return of setInterval() to clear it eventually
//REM: Binding the element instead, so that moveWord() can be used for all words the same
tListOfWords[i].dataset.Interval = setInterval(moveWord.bind(null, tListOfWords[i]), speed);
//REM: Adding event to stop the movement
//REM: Using onmouseup to omit keyboard input (tab + enter)
tListOfWords[i].onmouseup = function(){
clearInterval(this.dataset.Interval);
alert(this.id)
}
}
};
//REM: The .word not gets passed as parameter "element"
function moveWord(element){
//REM: style.transform has no sub properties
//REM: Using getBoundingClientRect() so the buttons entirely stay inside the box
var tPosition = element.getBoundingClientRect(),
tDirection = JSON.parse(element.dataset.Direction);
//REM Calculate the movement according to upperVelocity and lowerVelocity
//REM: Using different velocities for x, y to make less predictable and more dynamic
var tMovementX = Math.floor(Math.random() * (upperVelocity - lowerVelocity) + lowerVelocity),
tMovementY = Math.floor(Math.random() * (upperVelocity - lowerVelocity) + lowerVelocity);
//REM: Adding the direction of the element
tMovementX *= tDirection.x;
tMovementY *= tDirection.y;
//REM: Checking x
if(
(tPosition.left + tMovementX) <= bounds.left ||
(tPosition.right + tMovementX) >= bounds.right
){
tDirection.x *= -1;
tMovementX *= -1;
//REM: Storing the changed direction
element.dataset.Direction = JSON.stringify(tDirection)
};
//REM: Checking y
if(
(tPosition.top + tMovementY) <= bounds.top ||
(tPosition.bottom + tMovementY) >= bounds.bottom
){
tDirection.y *= -1;
tMovementY *= -1;
//REM: Storing the changed direction
element.dataset.Direction = JSON.stringify(tDirection)
};
//REM: Getting the actual left/top assigned to the style
//REM: Note that those are not the same values as tPosition.
var tLeftInsideParent = (parseFloat(element.style.left) || 0),
tTopInsideParent = (parseFloat(element.style.top) || 0);
element.style.left = tLeftInsideParent + tMovementX + "px";
element.style.top = tTopInsideParent + tMovementY + "px"
};
//REM: Adjusting the bounds on scrolling and resizing
window.onscroll = window.onresize = function(){
//REM: Calculating the bounds
bounds = document.querySelector(".wordGameContainer").getBoundingClientRect()
};
.word{
position: relative
}
.wordGameContainer{
background: #1390ff;
height: 150px;
width: 400px;
}
<div class="wordGameContainerHeader">
<h1>Word Wizard</h1>
<h4>WORD TO FIND</h4>
</div>
<div>
<button onclick="startGame()" class="playButton">PLAY</button>
</div>
<div class="wordGameContainer">
<!--REM: Why is the "class" used like an "id"? -->
<button id="word1" class="word">WORD 1</button>
<button id="word2" class="word">WORD 2</button>
<button id="word3" class="word">WORD 3</button>
<button id="word4" class="word">WORD 4</button>
</div>
Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling..