BgMusic.vue 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <template>
  2. <div
  3. class="bg-music"
  4. :class="{ ['icon-playing']: playing }"
  5. @click="handleClick"
  6. v-show="data.value.show"
  7. >
  8. <audio
  9. :src="data.value.url"
  10. ref="audioRef"
  11. loop
  12. @loadedmetadata="data.value.show = true"
  13. @play="handlePlay"
  14. ></audio>
  15. </div>
  16. </template>
  17. <script>
  18. import { onMounted, ref } from 'vue'
  19. export default {
  20. setup() {
  21. const { origin, pathname } = window.location
  22. let data = ref({
  23. show: false,
  24. playing: false,
  25. url: `${origin}${pathname}music/bg.mp3`
  26. })
  27. onMounted(() => {
  28. document.body.addEventListener('click', this.handleClick)
  29. this.$nextTick(() => {
  30. this.handleIOSAudio()
  31. })
  32. })
  33. const handleIOSAudio = () => {
  34. const isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
  35. if (isiOS) {
  36. document.addEventListener(
  37. 'WeixinJSBridgeReady',
  38. () => {
  39. this.$refs.audioRef.load()
  40. },
  41. false
  42. )
  43. }
  44. }
  45. const handleClick = () => {
  46. if (!this.show || !this.$refs.audioRef) return
  47. if (this.playing) {
  48. this.$refs.audioRef.pause()
  49. } else {
  50. this.$refs.audioRef.play()
  51. }
  52. this.playing = !this.playing
  53. }
  54. const handlePlay = () => {
  55. document.body.removeEventListener('click', this.handleClick)
  56. }
  57. return {
  58. data,
  59. handleIOSAudio,
  60. handleClick,
  61. handlePlay
  62. }
  63. }
  64. }
  65. </script>
  66. <style lang="less" scoped>
  67. .bg-music {
  68. position: fixed;
  69. top: 1em;
  70. right: 1em;
  71. z-index: 10;
  72. width: 2em;
  73. height: 2em;
  74. background-image: url('~@/assets/ButtonImage/play.png');
  75. background-repeat: no-repeat;
  76. background-size: 100% 100%;
  77. &.icon-playing {
  78. background-image: url('~@/assets/indexImg/paused.png');
  79. animation: musicrotate 3s linear infinite;
  80. }
  81. & > audio {
  82. max-width: 1px;
  83. max-height: 1px;
  84. }
  85. }
  86. @keyframes musicrotate {
  87. 100% {
  88. transform: rotate(360deg);
  89. }
  90. }
  91. </style>