BgMusic.vue 1.7KB

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