方法一:通过background-position、background-image、backg-repeat三个属性以及jquery animate()方法改变背景骰子图来实现图片切换。
PS:调整background-position比较麻烦,由于背景是一张包含各个点数以及旋转时骰子的整图
方法二:设置定时调整css样式background-image。
PS:实现简单,但是视觉效果不佳
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>掷骰子</title> <style type="text/css"> .dice { width: 100px; height: 100px; background-image: url(dice_1.jpg); cursor: pointer; position: relative; } </style> </head> <body> <div></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <script type="text/javascript"> $(function(){ let dice = $(".dice"); dice.on('click',function(){ dice.css('cursor', 'default'); let num =Math.ceil(Math.random()*6); console.log(num); dice.css('background-image', 'url(dice_f.jpg)'); setTimeout(function(){ dice.css('background-image', 'url(dice_s.jpg)'); },200); setTimeout(function(){ dice.css('background-image', 'url(dice_t.jpg)'); },200); setTimeout(function(){ dice.css('background-image', 'url(dice_'+num+'.jpg)') }, 200); }); }); </script> </body> </html>
骰子图:
效果图: