vue自定義視頻播放組件

H5支持video標(biāo)簽肄程,但是默認(rèn)樣式難以滿足日常需求,早晚都要做,就先寫個(gè)demo出來方便以后使用了绷耍。

效果預(yù)覽

使用前需要了解的鼠標(biāo)交互事件鏈接https://blog.csdn.net/zeping891103/article/details/70208945
關(guān)于視頻播放相關(guān)的有疑問的可以結(jié)合的音樂播放器那章一起看http://www.reibang.com/p/75d160a6cbbd

頁面引用

<template>
  <div class="home-page">
    <mvideo :videoSrc.sync="url"></mvideo>
    <Button @click="ChangeUrl">切換</Button>
  </div>
</template>
import Mvideo from '@/components/videoPlay'
export default {
  data() {
    return {
      url: '../../asset/video/video_01.mp4'
    };
  }, 
 components: {
      Mvideo,
  },
  methods: {
    ChangeUrl(){
      this.url = '../../asset/video/video_02.mp4'
    }
  },
}

組件部分--首先有一個(gè)總?cè)萜魍孪蓿瑅ideo和自定義的控制條

<div class="main-container" ref="vcontainer">
    <video class="video-player" preload="preload" id="video" ref="v">
      <source :src="videoSrc" />
    </video>
    <div ref="track" style="width: 100%"></div>
    <transition name="fade">
      <div class="controller" v-show="isControlVisible"> </div>
    </transition>
</div>

視頻部分不用處理了,主要是自定義底部控制條的樣式褂始,這里就看各位八仙過海了诸典。
組件內(nèi)部用到的一些變量

  data() {
    return {
      isControlVisible: false,  //自定義控制器是否可見
      isPaused: true,  //是否暫停
      isDragging: false,  //是否拖拽進(jìn)度條
      currentTime: "00:00",  //當(dāng)前播放時(shí)間
      videoDuration: 0, //視頻時(shí)長
      videoProgress: 0, //視頻進(jìn)度百分比  0-1
      thumbTranslateX: 0, // 進(jìn)度條滑塊位置
      hidingEvent: null,
    };
  },

首先是播放時(shí)間/視頻時(shí)長+進(jìn)度條

        <div class="controller_btn-wrapper">
          <div class="controller_btn" @click="Playing">
            <img
              v-show="isPaused"
              class="play-icon"
              src="@asset/icon/play_01.png"
            />
            <img
              v-show="!isPaused"
              class="play-icon"
              src="@asset/icon/play_02.png"
            />
          </div>
視頻播放進(jìn)度
          <div class="controller_time">
            {{ currentTime }} / {{ videoDuration }}
          </div>
全屏按鈕
          <div class="fullScreen">
            <img @click="ToggleFullscreen" src="@assets/icon_02.png" alt="" />
          </div>
        </div>
        進(jìn)度條部分
        <div
          class="progress-container"
          id="progress"
          @click="handleProgressClick($event)"
          @pointerup="stopDragging"
        >
          <div class="progress_box" :style="{ width: videoProgressPercent }">
            <div
              class="play_point"
              :style="{ transform: 'translateX(' + thumbTranslateX + 'px)' }"
              @pointerdown="startDragging($event)"
            >
              <img src="@assets/icon_01.png" alt="" />
            </div>
          </div>
        </div>

進(jìn)度條思路是外層div設(shè)置背景色,內(nèi)部進(jìn)度條width實(shí)時(shí)變化達(dá)到進(jìn)度的效果
我的樣式設(shè)置

    .progress-container {
      position: absolute;
      width: 100%;
      top: -2.5px;
      height: 5px;
      background: rgba(255, 255, 255, 0.5);
      z-index: 100;
      cursor: pointer;
      .progress_box {
        z-index: 99;
        position: relative;
        background: #409eff;
        height: 5px;
        .play_point {
          transition: -webkit-transform 0.2s linear;
          transition: transform 0.2s linear;
          transition: transform 0.2s linear, -webkit-transform 0.2s linear;
          position: absolute;
          top: -7px;
          left: 0;
          width: 20px;
          background: #fff;
          border-radius: 3px;
          display: flex;
          align-items: center;
          justify-content: center;
          img {
            width: 18px;
            cursor: pointer;
          }
        }
      }
    }
  mounted() {
    // 一定要放在mounted定義video
    const video = document.getElementById("video");
    this.videoInit();
  },
  computed: {
    //計(jì)算屬性--獲取進(jìn)度條已播放進(jìn)度0-100%
    videoProgressPercent() {
      return `${this.videoProgress * 100}%`;
    },
  },
  methods() {
    videoInit() {
      let that = this;
      let progressL = this.$refs.track.offsetWidth; // 進(jìn)度條總長
      // 音頻或視頻文件已經(jīng)就緒可以開始
      video.addEventListener("canplay", () => {
        that.videoDuration = that.timeToString(video.duration);
      });
      video.addEventListener("timeupdate", () => {
        // 當(dāng)前播放時(shí)間
        that.currentTime = that.timeToString(video.currentTime);
        that.videoProgress = video.currentTime / video.duration;
        that.thumbTranslateX = (that.videoProgress * progressL).toFixed(3);
      });
      video.addEventListener("ended", () => {
        setTimeout(() => {
          video.play();
        }, 100);
      });
    },
    // 秒值轉(zhuǎn)字符串
    timeToString(param) {
      param = parseInt(param);
      let hh = "",
        mm = "",
        ss = "";
      if (param >= 0 && param < 60) {
        param < 10 ? (ss = "0" + param) : (ss = param);
        return "00:" + ss;
      } else if (param >= 60 && param < 3600) {
        mm = parseInt(param / 60);
        mm < 10 ? (mm = "0" + mm) : mm;
        param - parseInt(mm * 60) < 10
          ? (ss = "0" + String(param - parseInt(mm * 60)))
          : (ss = param - parseInt(mm * 60));
        return mm + ":" + ss;
      }
    },
  },

到這步崎苗,就實(shí)現(xiàn)了播放暫停+播放時(shí)間進(jìn)度+進(jìn)度條狐粱;

接著是點(diǎn)擊進(jìn)度條控制視頻時(shí)間和拖拽進(jìn)度按鈕實(shí)現(xiàn)視頻跳轉(zhuǎn)進(jìn)度

先點(diǎn)擊進(jìn)度條來實(shí)現(xiàn)跳轉(zhuǎn)

    //點(diǎn)擊進(jìn)度條
    handleProgressClick(event) {
      let progressL = this.$refs.track.offsetWidth; // 進(jìn)度條總長
      let clickX = event.offsetX;
      console.log(clickX, progressL);
      let time = (clickX / progressL).toFixed(2);
      this.setProgress(time);
    },
    setProgress(x) {
      video.currentTime = video.duration * x;
    },

拖拽進(jìn)度條--需要給最外層容器添加@pointermove.prevent事件

  <div
    class="main-container"
    @pointermove.prevent="handleMouseMove($event)"
    ref="vcontainer"
  >
  </div>
    handleMouseMove(event) {
      this.showControlBar();
      this.showCursor();
      if (this.hidingEvent !== null) {
        clearInterval(this.hidingEvent);
      }
      this.hidingEvent = setInterval(this.hideControlBar, 3000);//鼠標(biāo)禁止不動3秒關(guān)閉自定義控制條
      this.moveDragging(event);
    },
    //展示控制條
    showControlBar() {
      this.isControlVisible = true;
    },
    //關(guān)閉控制條
    hideControlBar() {
      const isFullscreen = document.webkitIsFullScreen || document.fullscreen;
      if (isFullscreen) {
        this.hideCursor();
      }
      this.isControlVisible = false;
    },
    hideCursor() {
      document.body.style.cursor = "none";
    },
    showCursor() {
      document.body.style.cursor = "default";
    },
    moveDragging(event) {},
    //開始拖拽
    startDragging(event) {
      this.PauseVideo();
      this.isDragging = true;
    },
    //停止拖拽
    stopDragging() {
      this.isDragging = false;
      this.PlayVideo();
    },

最后加上鼠標(biāo)移入移出來展示和關(guān)閉控制條

  <div
    class="main-container"
    @pointermove.prevent="handleMouseMove($event)"
    @pointerleave="handleMouseLeave"
    @pointerenter="handleMouseEnter"
    ref="vcontainer"
  >
  </div>
    handleMouseLeave() {
      this.hideControlBar();
    },
    //隱藏顯示控制條
    handleMouseEnter() {
      this.showControlBar();
    },
    //全屏方法
    ToggleFullscreen() {
      const isFullscreen = document.webkitIsFullScreen || document.fullscreen;
      if (isFullscreen) {
        const exitFunc =
          document.exitFullscreen || document.webkitExitFullscreen;
        exitFunc.call(document);
      } else {
        const element = this.$refs.vcontainer;
        const fullscreenFunc =
          element.requestFullscreen || element.webkitRequestFullScreen;
        fullscreenFunc.call(element);
      }
    },

組件完整代碼--css+html+js

<style lang="less" scoped>
.main-container {
  position: relative;
  .video-player {
    width: 100%;
    display: flex;
  }
  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 0.8s;
  }
  .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
    opacity: 0;
  }
  .controller {
    flex-direction: column;
    height: 50px;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.5);
    .controller_btn-wrapper {
      position: relative;
      height: 50px;
      display: flex;
      align-items: center;
      color: #fff;
      padding: 0 18px;
      .controller_btn {
        cursor: pointer;
        transition: 0.5s;
        margin: 7px 20px;
        .play-icon {
          margin-top: 2px;
          width: 36px;
          height: 36px;
        }
      }
      .fullScreen {
        transition: 0.5s;
        position: absolute;
        right: 0;
        top: 0;
        width: 80px;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        img {
          width: 36px;
          height: 36px;
          cursor: pointer;
        }
      }
      .controller_btn:hover {
        color: #409eff;
      }
      .controller_time {
        width: 100px;
        height: 100%;
        line-height: 50px;
      }
    }
    .process-container {
      position: absolute;
      width: 100%;
      top: -2.5px;
      height: 5px;
      background: rgba(255, 255, 255, 0.5);
      z-index: 100;
      cursor: pointer;
      .progress_box {
        z-index: 99;
        position: relative;
        background: #409eff;
        height: 5px;
        .play_point {
          transition: -webkit-transform 0.2s linear;
          transition: transform 0.2s linear;
          transition: transform 0.2s linear, -webkit-transform 0.2s linear;
          position: absolute;
          top: -7px;
          left: 0;
          width: 20px;
          background: #fff;
          border-radius: 3px;
          display: flex;
          align-items: center;
          justify-content: center;
          img {
            width: 18px;
            cursor: pointer;
          }
        }
      }
    }
  }
}
</style>

<template>
  <div
    class="main-container"
    @pointermove.prevent="handleMouseMove($event)"
    @pointerleave="handleMouseLeave"
    @pointerenter="handleMouseEnter"
    ref="vcontainer"
  >
    <video class="video-player" preload="preload" id="video" ref="v">
      <source :src="videoSrc" />
    </video>
    <div ref="track" style="width: 100%"></div>
    <transition name="fade">
      <div class="controller" v-show="isControlVisible">
        <div class="controller_btn-wrapper">
          <div class="controller_btn" @click="Playing">
            <img
              v-show="isPaused"
              class="play-icon"
              src="../../pic/icon_01.png"
            />
            <img
              v-show="!isPaused"
              class="play-icon"
              src="../../pic/icon_02.png"
            />
          </div>
          <div class="controller_time">
            {{ currentTime }} / {{ videoDuration }}
          </div>
          <div class="fullScreen">
            <img @click="ToggleFullscreen" src="@assets/icon_02.png" alt="" />
          </div>
        </div>
        <div
          class="process-container"
          id="progress"
          @click="handleProgressClick($event)"
          @pointerup="stopDragging"
        >
          <div class="progress_box" :style="{ width: videoProgressPercent }">
            <div
              class="play_point"
              :style="{ transform: 'translateX(' + thumbTranslateX + 'px)' }"
              @pointerdown="startDragging($event)"
            >
              <img src="@assets/icon_01.png" alt="" />
            </div>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>
<script>
export default {
  name: "MyVideo",
  props: {
    videoSrc: {
      type: String,
      default:
        "@asset/video/video_01.mp4",
    },
  },
  data() {
    return {
      isControlVisible: false,
      isPaused: true,
      isDragging: false,
      currentTime: "00:00",
      videoDuration: 0,
      videoProgress: 0,
      thumbTranslateX: 0, // 進(jìn)度條滑塊位置
      hidingEvent: null,
    };
  },
  created() {},
  mounted() {
    const video = document.getElementById("video");
    this.videoInit();
  },
  computed: {
    videoProgressPercent() {
      return `${this.videoProgress * 100}%`;
    },
    getUrl() {
      return this.videoSrc;
    },
  },
  watch: {
    getUrl(curval, oldval) {
      console.log(`最新值${curval}--舊值${oldval}`);
      this.PlayNew(curval);
    },
  },
  methods: {
    videoInit() {
      let that = this;
      let progressL = this.$refs.track.offsetWidth; // 進(jìn)度條總長
      // 音頻或視頻文件已經(jīng)就緒可以開始
      video.addEventListener("canplay", () => {
        that.videoDuration = that.timeToString(video.duration);
      });
      video.addEventListener("timeupdate", () => {
        // 當(dāng)前播放時(shí)間
        that.currentTime = that.timeToString(video.currentTime);
        that.videoProgress = video.currentTime / video.duration;
        that.thumbTranslateX = (that.videoProgress * progressL).toFixed(3);
      });
      video.addEventListener("ended", () => {
        setTimeout(() => {
          video.play();
        }, 100);
      });
    },
    //url地址變化后重新加載視頻
    PlayNew(val) {
      this.isPaused = false
      video.src = this.videoSrc
      setTimeout(() => {
        this.totalTime = "00:00";
        video.play();
      }, 100);
    },
    Playing() {
      if (video.paused) {
        this.PlayVideo();
      } else {
        this.PauseVideo();
      }
    },
    handleEnd() {
      this.PauseVideo();
    },
    //播放
    PlayVideo() {
      this.isPaused = false;
      video.play();
    },
    //暫停
    PauseVideo() {
      this.isPaused = true;
      video.pause();
    },
    // 秒值轉(zhuǎn)字符串
    timeToString(param) {
      param = parseInt(param);
      let hh = "",
        mm = "",
        ss = "";
      if (param >= 0 && param < 60) {
        param < 10 ? (ss = "0" + param) : (ss = param);
        return "00:" + ss;
      } else if (param >= 60 && param < 3600) {
        mm = parseInt(param / 60);
        mm < 10 ? (mm = "0" + mm) : mm;
        param - parseInt(mm * 60) < 10
          ? (ss = "0" + String(param - parseInt(mm * 60)))
          : (ss = param - parseInt(mm * 60));
        return mm + ":" + ss;
      }
    },
    //隱藏顯示控制條
    handleMouseEnter() {
      this.showControlBar();
    },
    handleMouseMove(event) {
      this.showControlBar();
      this.showCursor();
      if (this.hidingEvent !== null) {
        clearInterval(this.hidingEvent);
      }
      this.hidingEvent = setInterval(this.hideControlBar, 3000);
      this.moveDragging(event);
    },
    handleMouseLeave() {
      this.hideControlBar();
    },
    //展示控制條
    showControlBar() {
      this.isControlVisible = true;
    },
    //關(guān)閉控制條
    hideControlBar() {
      const isFullscreen = document.webkitIsFullScreen || document.fullscreen;
      if (isFullscreen) {
        this.hideCursor();
      }
      this.isControlVisible = false;
    },
    hideCursor() {
      document.body.style.cursor = "none";
    },
    showCursor() {
      document.body.style.cursor = "default";
    },
    //點(diǎn)擊進(jìn)度條
    handleProgressClick(event) {
      let progressL = this.$refs.track.offsetWidth; // 進(jìn)度條總長
      let clickX = event.offsetX;
      console.log(clickX, progressL);
      let time = (clickX / progressL).toFixed(2);
      this.setProgress(time);
    },
    setProgress(x) {
      video.currentTime = video.duration * x;
    },
    //拖拽進(jìn)度條
    startDragging(event) {
      this.PauseVideo();
      this.isDragging = true;
    },
    moveDragging(event) {},
    stopDragging() {
      this.isDragging = false;
      this.PlayVideo();
    },
    ToggleFullscreen() {
      const isFullscreen = document.webkitIsFullScreen || document.fullscreen;
      if (isFullscreen) {
        const exitFunc =
          document.exitFullscreen || document.webkitExitFullscreen;
        exitFunc.call(document);
      } else {
        const element = this.$refs.vcontainer;
        const fullscreenFunc =
          element.requestFullscreen || element.webkitRequestFullScreen;
        fullscreenFunc.call(element);
      }
    },
  },
};
</script>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市胆数,隨后出現(xiàn)的幾起案子肌蜻,更是在濱河造成了極大的恐慌,老刑警劉巖必尼,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蒋搜,死亡現(xiàn)場離奇詭異,居然都是意外死亡判莉,警方通過查閱死者的電腦和手機(jī)豆挽,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來券盅,“玉大人帮哈,你說我怎么就攤上這事∶潭疲” “怎么了娘侍?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長泳炉。 經(jīng)常有香客問我憾筏,道長,這世上最難降的妖魔是什么胡桃? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任踩叭,我火速辦了婚禮,結(jié)果婚禮上翠胰,老公的妹妹穿的比我還像新娘。我一直安慰自己自脯,他們只是感情好之景,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著膏潮,像睡著了一般锻狗。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天轻纪,我揣著相機(jī)與錄音油额,去河邊找鬼。 笑死刻帚,一個(gè)胖子當(dāng)著我的面吹牛潦嘶,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播崇众,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼掂僵,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了顷歌?” 一聲冷哼從身側(cè)響起锰蓬,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎眯漩,沒想到半個(gè)月后芹扭,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡赦抖,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年舱卡,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片摹芙。...
    茶點(diǎn)故事閱讀 39,696評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡灼狰,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出浮禾,到底是詐尸還是另有隱情交胚,我是刑警寧澤,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布盈电,位于F島的核電站蝴簇,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏匆帚。R本人自食惡果不足惜熬词,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望吸重。 院中可真熱鬧互拾,春花似錦、人聲如沸嚎幸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽嫉晶。三九已至骑疆,卻和暖如春田篇,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背箍铭。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工泊柬, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人诈火。 一個(gè)月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓兽赁,卻偏偏與公主長得像,于是被迫代替她去往敵國和親柄瑰。 傳聞我的和親對象是個(gè)殘疾皇子闸氮,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,592評論 2 353