example_of_js_3.html 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>双色球随机选号</title>
  6. <style>
  7. p {
  8. width: 100px;
  9. height: 100px;
  10. color: white;
  11. font: 60px/100px Arial;
  12. border-radius: 50px;
  13. text-align: center;
  14. float: left;
  15. margin-left: 10px;
  16. }
  17. .red {
  18. background-color: red;
  19. }
  20. .blue {
  21. background-color: blue;
  22. }
  23. </style>
  24. </head>
  25. <body>
  26. <!-- 浏览器中的JavaScript包含以下三样内容 -->
  27. <!-- ECMAScript - ES6 - 核心语法 -->
  28. <!-- BOM - 浏览器对象模型 - window -->
  29. <!-- DOM - 文档对象模型 - document -->
  30. <script>
  31. function outputBall(num, color='red') {
  32. document.write(`<p class="${color}">`)
  33. if (num < 10) {
  34. document.write('0')
  35. }
  36. document.write(num)
  37. document.write('</p>')
  38. }
  39. var selectedBalls = []
  40. while (selectedBalls.length < 6) {
  41. let num = parseInt(Math.random() * 33 + 1)
  42. if (selectedBalls.indexOf(num) == -1) {
  43. selectedBalls.push(num)
  44. }
  45. }
  46. // 给红色球排序 - 需要传入一个匿名函数给出比较元素的规则
  47. // ES6开始支持使用箭头函数(Lambda函数 - 匿名函数)
  48. selectedBalls.sort((x, y) => x - y)
  49. // 代码有很多种坏味道 重复是最坏的一种 - Martin Fowler
  50. selectedBalls.forEach(item => outputBall(item))
  51. let num = parseInt(Math.random() * 16 + 1)
  52. outputBall(num, 'blue')
  53. </script>
  54. </body>
  55. </html>