我点击一个按钮时试图让轮盘旋转,但我似乎无法将我的js文件生成的随机数传递给css
JS
function roulette_spin(btn){
var rand = Math.floor(Math.random() * 720) + 540;
$('.roulette_wheel').css('transform','rotate('+rand+'deg)');
}
HTML
<body>
<div class="roulette_wheel" style="z-index: 0;">
<img src="ayy.jpg" width="500px" height="500px" />
<button value="spin" onclick="roulette_spin(this)">SPIN</button>
</div>
我会说roulette_wheel类没有分配给正确的元素,即图像。除了设置旋转变换不会使车轮旋转,但只会改变其旋转角度一次(此处没有任何过渡)。
下面是一个在动画过程中指定变换样式的工作示例。
JQuery调用被香草选择器(getElementsByClassName,getElementById)和style对象操作取代,而不是JQuery的css
方法。
另外,查看requestAnimationFrame的文档
(好吧,我在这里有点无聊:))
var force = 0;
var angle = 0;
var inertia = 0.985;
var minForce = 15;
var randForce = 15;
var rouletteElem = document.getElementsByClassName('roulette_wheel')[0];
var scoreElem = document.getElementById('score');
var values = [
0,27,10,25,29,12,8,19,31,18,6,21,33,16,4,
23,35,14,2,0,28,9,26,30,11,7,20,32,17,5,
22,34,15,3,24,36,16,1
].reverse();
function roulette_spin(btn){
// set initial force randomly
force = Math.floor(Math.random() * randForce) + minForce;
requestAnimationFrame(doAnimation);
}
function doAnimation() {
// new angle is previous angle + force modulo 360 (so that it stays between 0 and 360)
angle = (angle + force) % 360;
// decay force according to inertia parameter
force *= inertia;
rouletteElem.style.transform = 'rotate('+angle+'deg)';
// stop animation if force is too low
if (force < 0.05) {
// score roughly estimated
scoreElem.innerHTML = values[Math.floor(((angle / 360) * values.length) - 0.5)];
return;
}
requestAnimationFrame(doAnimation);
}
<body>
<div style="z-index: 0; position: relative">
<img class="roulette_wheel" src="http://pngimg.com/uploads/roulette/roulette_PNG14.png" width="300px" height="300px" />
<div style="position: absolute; top: 0px; left: 150px; background-color: red; width: 1px; height: 40px;"></div>
<button value="spin" onclick="roulette_spin(this)">SPIN</button>
<span id="score"></span>
</div>
这是一个工作示例,其中包含对代码的一些更新。
就像@ H.Figueiredo建议的那样,我已经将旋转选择器更改为img
以避免按钮的旋转。
HTML
<div class="roulette_wheel" style="z-index: 0;">
<img src="https://picsum.photos/200/300" width="500px" height="500px" />
<button class="spin" value="spin">SPIN</button>
</div>
CSS
function roulette_spin(btn){
var rand = Math.floor(Math.random() * 720) + 540;
$('.roulette_wheel img').css('transform','rotate('+rand+'deg)');
}
$('.spin').click(function(){
roulette_spin($(this).siblings('img'));
});
试试这个:
<html>
<body>
<div class="roulette_wheel" style="z-index: 0;">
<img src="ayy.jpg" width="500px" height="500px" />
<button value="spin" onclick="roulette_spin()">SPIN</button>
</div>
<script>
function roulette_spin(){
var rand = Math.floor(Math.random() * 720) + 540;
document.querySelector('.roulette_wheel').style.transform = 'rotate('+rand+'deg)';
}
</script>
</body>
</html>