如何将 css 媒体查询应用于视频海报



多亏了这个答案,我在 css 中使用video[poster]{object-fit:fill}以避免 html5 视频中的海报图像失真。由于poster看起来很时尚,我还想使用 css 根据屏幕尺寸(移动或桌面(显示视频的不同海报。但video[poster]{background-image:url(poster.jpg)不会产生任何结果,大概poster不是背景。所以我尝试改编一些在这里找到的javascript,如下所示:

function myFunction(x) {
  if (x.matches) { // If media query matches
    document.getElementById("video").poster = "poster1.jpg";
  } else {
    document.getElementById("video").poster = "poster2.jpg";
  }
}
var x = window.matchMedia("(max-width: 700px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction)

它也不起作用,但也许它只是缺少一些小东西(即使是原始的 javascript 验证失败(有人知道如何将媒体查询应用于海报属性吗?

删除 myFunction(x) 中的x

API已经改变,现在它将是一个事件,你将在这里收到,而在以前的实现中,它确实是MediaQueryList。

只要保留对MediaQueryList的引用,你应该没问题。

function myFunction(evt) {
  console.log(evt && evt.toString());
  if (x.matches) { // If media query matches
    document.getElementById("video").poster = "https://lorempixel.com/200/400";
  } else {
    document.getElementById("video").poster = "https://lorempixel.com/400/200";
  }
}
var x = window.matchMedia("(max-width: 500px)")
myFunction() // Call listener function at run time
x.addListener(myFunction)
.as-console-wrapper{max-height:20px!important}
<video id="video" controls></video>

最新更新