仅在桌面

时间:2016-05-30 16:45:36

标签: javascript jquery html video html5-video

我有这个代码,如果用户不在移动设备上,则填充源的src属性:

 if($.browser.mobile)
   {
       console.log("is mobile")
      // it is mobile browser
   }
   else
   {
     console.log("is desktop")
      // no mobile browser
      var sources = document.querySelectorAll('video#patient-video source');
     // Define the video object this source is contained inside
     var video = document.querySelector('video#patient-video');
     for(var i = 0; i<sources.length;i++) {
       sources[i].setAttribute('src', sources[i].getAttribute('data-src'));
     }
     // If for some reason we do want to load the video after, for desktop as opposed to mobile (I'd imagine), use videojs API to load
     video.load();
     video.muted= "muted";
   }

要检查它是否是移动浏览器,我使用插件:

detectmobilebrowser.js

我的HTML如下:

 <video id="patient-video" width="100%" preload="none" poster="../../assets/img/patient-home-1600.jpg" autoplay loop>
            <source data-src="../../assets/video/patient-home-video-comp.mp4" src="" type="video/mp4">
            <source data-src="../../assets/video/patient-home-video-comp.webm" src="" type="video/webm">
            <source data-src="../../assets/video/patient-home-video-comp.ogv" src="" type="video/ogg">
          </video>

这适用于某个特定视频,但我如何调整Javscript以便对页面上的所有视频执行相同的操作。

1 个答案:

答案 0 :(得分:6)

如果您使用多个同名视频

,则应使用非ID的类
if($.browser.mobile)
   {
       console.log("is mobile")
      // it is mobile browser
   }
   else
   {
     console.log("is desktop")
      // no mobile browser
      var sources = document.querySelectorAll('video.patient-video source');
     // Define the video object this source is contained inside
     var video = document.querySelector('video.patient-video');
     for(var i = 0; i<sources.length;i++) {
       sources[i].setAttribute('src', sources[i].getAttribute('data-src'));
     }
     // If for some reason we do want to load the video after, for desktop as opposed to mobile (I'd imagine), use videojs API to load
     video.load();
     video.muted= "muted";
   }

注意点而不是哈希标记。你之前甚至不需要“视频”。不要忘记相应地更新您的HTML

应该是

<video class="patient-video" width="100%" preload="none" poster="../../assets/img/patient-home-1600.jpg" autoplay loop>
            <source data-src="../../assets/video/patient-home-video-comp.mp4" src="" type="video/mp4">
            <source data-src="../../assets/video/patient-home-video-comp.webm" src="" type="video/webm">
            <source data-src="../../assets/video/patient-home-video-comp.ogv" src="" type="video/ogg">
          </video>