我正在制作一個基本的目標教練游戲。我有一個游戲板,它只是一個帶有范圍的 div 和一個實際上只是一個按鈕的目標圖示。我希望按鈕在每次單擊時都在范圍內移動。
這是我的游戲板和目標代碼
function targetClicked() {
score ;
document.getElementById("scoreLabel").innerHTML = score;
moveTarget();
}
function moveTarget() {
}
#gameboard {
display: block;
margin-left: auto;
margin-right: auto;
margin-top: 50px;
width: 500px;
height: 500px;
background-color: darkgray;
}
#target {
width: 75px;
height: 75px;
position: absolute;
left: 50%;
margin-right: -50%;
transform: translate(-50%, 50%);
}
<div id="gameboard">
<input hidden type="image" src="target.png" id="target" onclick="targetClicked()">
</div>
其他一切,如倒數計時器和計分器都可以作業。(此處未顯示)當計數器達到 0 時,我什至讓游戲板和所有東西都消失了,但我實際上并不知道每次單擊目標時如何移動目標。
我可以使用這樣的東西并在 moveTarget 函式中調整按鈕位置的屬性嗎?
有沒有更好的方法來解決它,或者我可以簡單地讓按鈕在點擊時移動它的位置?
uj5u.com熱心網友回復:
歡迎來到 StackOverflow。有很多方法可以做到這一點。您可以在單擊時設定元素的,并使用上面已經使用的style屬性來設定目標的位置。例如:targettransform
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function targetClicked() {
const randX = getRandomInt(100);
const randY = getRandomInt(100);
document.getElementById("target").style.transform = `translate(${randX}%, ${randY}%)`;
}
如果您想了解更多資訊,您可能想查看通過 CSS 設定位置的所有不同方式。希望這能讓你起步。
uj5u.com熱心網友回復:
你好 justinMonserrat,我希望這能幫助你解決問題,通過這個你可以將影像移動到父元素內的任何位置。
function randomAxis(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min 1)) min;
}
const img = document.getElementById("gameboard_target");
const gameboard = document.getElementById("gameboard").getBoundingClientRect();
const img_credentials = img.getBoundingClientRect();
const g_width = gameboard.width-img_credentials.width;
const g_height = gameboard.height-img_credentials.height;
img.onclick = function(){
const y_axis = randomAxis(0,g_width);
const x_axis = randomAxis(0,g_height);
this.style.cssText = `transform:translate(${x_axis}px,${y_axis}px)`
};
#gameboard{
border:2px solid;
width:300px;
height:300px;
background-color: darkgray;
}
#gameboard img{
width:30px;
height:30px;
border-radius: 50%;
transition: transform .5s cubic-bezier(.22,.61,.36,1);
cursor:pointer;
}
#gameboard img:active{
box-shadow: 0px 0px 13px 3px #ecebeb;
}
<div id="gameboard">
<img id="gameboard_target" src="https://justinmonserrat.github.io/target-practice/target.png" />
</div>
uj5u.com熱心網友回復:
輸入型別不是按鈕,而是影像。你想移動影像嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/525390.html
下一篇:CSS用影像或svg替換文本
