我正在尝试使用HTML,CSS和Javascript制作轮盘游戏。
调整浏览器窗口大小时出现问题。
链接:https://jsfiddle.net/5wrfzbaj/3/
背景图像随其移动,并且由于显示了该行。轮盘停止播放后,它会显示不同的颜色,具体取决于您的浏览器大小。
我希望背景图像被固定在赢球线上,但我真的不知道该怎么做。
HTML:
<main>
<h1>Rulette</h1>
<div class="rolling-area">
<div class="rolling-indicator"></div>
<div class="rolling-box"></div>
</div>
</main>
<script src="roll.js"></script>
CSS:
* {
box-sizing: border-box;
}
h1{
margin-top: 100px;
text-align: center;
}
.rolling-area{
width: 100%;
margin: auto;
border: 1px solid rgb(0,0,0,.5);
position: relative;
margin-top: 50px;
padding: 10px;
}
.rolling-box {
width: 100%;
height: 100px;
background-image: url(https://i.imgur.com/P0oti92.png);
background-repeat: repeat-x;
background-size: auto 100px;
background-position: 520px;
transition: 8s;
}
.rolling-indicator{
position: absolute;
background-color: rgb(0,0,0,.5);
width: 3px;
left: 50%;
top: -15px;
height: calc(100% + 30px);
}
JavaScript:
let startingPosition = "520px";
let randomPosition;
let minimumPosition = 2000;
//Roll the rulette
function roll() {
console.log("Rolling!");
randomPosition = Math.floor(Math.random() * 15000 + minimumPosition);
console.log(randomPosition);
document.querySelector(".rolling-box").setAttribute("style", "background-position: " + randomPosition + "px center;");
}
// Restart the rulette to standart position
function positionZero() {
document.querySelector(".rolling-box").setAttribute("style", "background-position: 2000px center;" + " transition: 0s;");
console.log("Zero");
setTimeout(positionStandrad, 1);
}
function positionStandrad() {
document.querySelector(".rolling-box").setAttribute("style", "background-position: " + startingPosition + " center; transition: 1s ease-out;");
console.log("Standar");
}
//setInterval(roll, 1000);
答案 0 :(得分:0)
这可以通过更改background-position
属性以使用百分比值(50%)而不是像素(520px)来完成。对于偏移量,可以使用calc
函数:background-position: calc(50% + 2000px);
。
结果:https://jsfiddle.net/sLfyerd7/1/
其他更改:
startingPosition
更改为数字而不是字符串elem.style.backgroundPosition
代替elem.setAttribute('style', 'background-position: ...')