【问题标题】:How to remove the overlay image on only the selected lazyloaded video?如何仅删除所选延迟加载视频上的叠加图像?
【发布时间】:2022-01-20 17:40:25
【问题描述】:

在下面的脚本中,我正在延迟加载两个视频。我的脚本旨在在单击时从所选视频中删除覆盖图像。但是,它还会从第二个视频中删除覆盖图像并将其放置在其上方。再次单击会删除重复的图像,第三次单击会播放视频。

如何以不影响页面上第二个视频的方式仅删除所选视频的图像?

const getVideoId = (wistia_vid) => {
  const classes = Array.from(wistia_vid.querySelector(".wistia_embed").classList);
  const idClass = classes.find((cls) => cls.startsWith("wistia_async_"));
  const id = idClass.replace("wistia_async_", "");

  return id;
};

const removeElems = (wistia_vid) => {
  const toRemove = Array.from(
    wistia_vid.querySelectorAll(".wistia__overlay, .embed-youtube__play, .embed-video__play")
  );

  toRemove.forEach((node) => node.remove());
};

Array.from(document.querySelectorAll(".wistia")).forEach((node) => {
  node.addEventListener("click", () => {
    const videoId = getVideoId(node);
    let wistiaSupportScripts = [
      //adds jsonp file to provide security over requests
      `https://fast.wistia.com/embed/medias/${videoId}.jsonp`
    ];

    removeElems(node);
    
    //Checks if above scripts are already loaded, and if they are... they won't be loaded again
    const id = 'script-ev1';
    if (!document.getElementById(id)) {
      // const id = 'script-ev1';
      var script = document.createElement('script');
      script.id = id;
      script.onload = () => {
        console.log('Ev-1.js loaded and ready to go!');
      };
      script.src = `https://fast.wistia.com/assets/external/E-v1.js` ;
      document.getElementsByTagName('head')[0].appendChild(script);
    } else {
      console.log(`Ev-1.js script with id: ${videoId} already loaded.`);
    }     
    
    //loads supporting scripts into head
    for (var i = 0; i < wistiaSupportScripts.length; i++) {
      let wistiaSupportScript = document.createElement("script");
      wistiaSupportScript.src = wistiaSupportScripts[i];
      let complete = false;
      if (
        !complete &&
        (!this.readyState ||
          this.readyState == "loaded" ||
          this.readyState == "complete")
      ) {
        complete = true;
        console.log(`JSONP script was added.`);
      }

      let wistiaContainers = document.querySelector(".wistia");

      wistiaContainers ? document.getElementsByTagName("head")[0].appendChild(wistiaSupportScript) : console.log("No Wistia videos here.");
    }     

    window._wq = window._wq || [];
    _wq.push({
      //globally scoped
      id: videoId,
      options: {
        autoPlay: true,
        volume: 0.5
      },

      onReady: function (video) {
        playedOnce = true;
        video.popover.show();
        video.play();
      }
    });
  });
});
.wistia {
  position: relative;
  display: block;
  width: 100%;
  max-width: 500px;
  padding: 0;
  overflow: hidden;
  cursor: pointer;
}
.wistia__overlay {
  width: 100%;
  height: auto;
}
.wistia::before {
  display: block;
  content: "";
}
.wistia button.embed-youtube__play {
  background: url("https://nextiva.com/assets/svg/play-button.svg") no-repeat center center, rgba(33, 33, 33, 0.8);
  background-size: 40%;
  background-position: 55%;
  border: 0;
  border-radius: 50%;
  position: absolute;
  transition: all 0.2s ease;
  -webkit-transition: background 0.2s;
  width: 10%;
  aspect-ratio: 1/1;
  max-height: 15%;    
  cursor: pointer;
  z-index: 10;
  display: flex;
  justify-content: center;
  align-items: center;
  top: 50%;
  left: 50%;
  transform: translate3d(-50%, -50%, 0);
}
.wistia:hover button.embed-youtube__play,
.wistia button.embed-youtube__play:focus-visible,
.wistia button.embed-youtube__play:focus {
  background: url("https://nextiva.com/assets/svg/play-button.svg") no-repeat center center, #005fec;
  background-size: 40%;
  background-position: 55%;
}
.wistia_embed,
.wistia embed,
.wistia iframe {
  width: 100%;
  max-height: 100%;
}
<div class="wistia">
  <picture>
    <source srcset="https://embedwistia-a.akamaihd.net/deliveries/48f1d62d1ceddb4284ad9cf67c916235.jpg?auto=format&w=640" media="(min-width: 1200px)">
    <source srcset="https://embedwistia-a.akamaihd.net/deliveries/48f1d62d1ceddb4284ad9cf67c916235.jpg?auto=format&w=310" media="(min-width: 768px)">
    <img src="https://embedwistia-a.akamaihd.net/deliveries/48f1d62d1ceddb4284ad9cf67c916235.jpg?auto=format&w=310" alt="some text" class="wistia__overlay lazy" loading="lazy">
  </picture>
  <div class="wistia_embed wistia_async_vhkqhqhzyq videoFoam=true"></div>
  <button class="embed-youtube__play"></button>
</div>

<div class="wistia">
  <picture>
    <source srcset="https://embed-fastly.wistia.com/deliveries/2eab84ad71cf5acd9c7572d36667d255.jpg?auto=format&w=640" media="(min-width: 1200px)">
    <source srcset="https://embed-fastly.wistia.com/deliveries/2eab84ad71cf5acd9c7572d36667d255.jpg?auto=format&w=310" media="(min-width: 768px)">
    <img src="https://embed-fastly.wistia.com/deliveries/2eab84ad71cf5acd9c7572d36667d255.jpg?auto=format&w=310" alt="Some text" class="wistia__overlay lazy" loading="lazy">
  </picture>
  <div class="wistia_embed wistia_async_8ei13wuby7 videoFoam=true"></div>
  <button class="embed-youtube__play"></button>
</div>

【问题讨论】:

    标签: javascript wistia


    【解决方案1】:

    把它放在你的 CSS 中:

    .wistia_embed {
        display: none;
    }
    
    .wistia.shown .wistia_embed {
        display: block;
    }
    

    然后,把这个放到你的 JS 中:

    if (!node.classList.contains("shown")) {
        node.classList.add("shown");
    } else {
        return;
    }
    

    就在事件监听函数的开头。

    说明

    E-v1.js 脚本会同时显示所有视频,当您使用这段代码第一次单击加载此脚本时:

    const id = 'script-ev1';
    if (!document.getElementById(id)) {
        // const id = 'script-ev1';
        var script = document.createElement('script');
        script.id = id;
        script.onload = () => {
            console.log('Ev-1.js loaded and ready to go!');
        };
        script.src = `https://fast.wistia.com/assets/external/E-v1.js`;
        document.getElementsByTagName('head')[0].appendChild(script);
    } else {
        console.log(`Ev-1.js script with id: ${videoId} already loaded.`);
    }
    

    在加载此脚本之前,没有任何视频,只有 <source> 元素。你从不向你的 CSS 表明视频应该是不可见的;此后,它们默认可见,一旦E-v1.js 脚本加载它们。

    现在,当你在上面添加这个 CSS sn-p 时,你表明 .wistia_embed 元素,基本上是加载的视频,必须从一开始就看不见。

    通过这一行 JS 代码,点击时只会显示一个视频(设置 .shown 类,其中包含 .wistia_embed 的 display: block; 属性)。

    未定义video.popover

    我不太了解 Wistia API,但是浏览器告诉我没有 video.popover.show() 函数。也将其从您的代码中删除,否则第二个视频不会通过单击它来自动播放。

    onReady: function (video) {
        playedOnce = true;
        video.popover.show(); // remove
        video.play();
    }
    

    完整的工作代码

    const getVideoId = (wistia_vid) => {
        const classes = Array.from(wistia_vid.querySelector(".wistia_embed").classList);
        const idClass = classes.find((cls) => cls.startsWith("wistia_async_"));
        const id = idClass.replace("wistia_async_", "");
    
        return id;
    };
    
    const removeElems = (wistia_vid) => {
        const toRemove = Array.from(
            wistia_vid.querySelectorAll(".wistia__overlay, .embed-youtube__play, .embed-video__play")
        );
    
        toRemove.forEach((node) => node.remove());
    };
    
    Array.from(document.querySelectorAll(".wistia")).forEach((node) => {
        node.addEventListener("click", () => {
            if (!node.classList.contains("shown")) {
                node.classList.add("shown");
            } else {
                return;
            }
    
            const videoId = getVideoId(node);
            let wistiaSupportScripts = [
                //adds jsonp file to provide security over requests
                `https://fast.wistia.com/embed/medias/${videoId}.jsonp`
            ];
    
            removeElems(node);
    
            //Checks if above scripts are already loaded, and if they are... they won't be loaded again
            const id = 'script-ev1';
            if (!document.getElementById(id)) {
                // const id = 'script-ev1';
                var script = document.createElement('script');
                script.id = id;
                script.onload = () => {
                    console.log('Ev-1.js loaded and ready to go!');
                };
                script.src = `https://fast.wistia.com/assets/external/E-v1.js`;
                document.getElementsByTagName('head')[0].appendChild(script);
            } else {
                console.log(`Ev-1.js script with id: ${videoId} already loaded.`);
            }
    
            //loads supporting scripts into head
            for (var i = 0; i < wistiaSupportScripts.length; i++) {
                let wistiaSupportScript = document.createElement("script");
                wistiaSupportScript.src = wistiaSupportScripts[i];
                let complete = false;
                if (
                    !complete &&
                    (!this.readyState ||
                        this.readyState == "loaded" ||
                        this.readyState == "complete")
                ) {
                    complete = true;
                    console.log(`JSONP script was added.`);
                }
    
                let wistiaContainers = document.querySelector(".wistia");
    
                wistiaContainers ? document.getElementsByTagName("head")[0].appendChild(wistiaSupportScript) : console.log("No Wistia videos here.");
            }
    
            window._wq = window._wq || [];
            _wq.push({
                //globally scoped
                id: videoId,
                options: {
                    autoPlay: true,
                    volume: 0.5
                },
    
                onReady: function (video) {
                    playedOnce = true;
                    video.play();
                }
            });
        });
    });
    .wistia {
        position: relative;
        display: block;
        width: 100%;
        max-width: 500px;
        padding: 0;
        overflow: hidden;
        cursor: pointer;
    }
    
    .wistia__overlay {
        width: 100%;
        height: auto;
    }
    
    .wistia::before {
        display: block;
        content: "";
    }
    
    .wistia button.embed-youtube__play {
        background: url("https://nextiva.com/assets/svg/play-button.svg") no-repeat center center, rgba(33, 33, 33, 0.8);
        background-size: 40%;
        background-position: 55%;
        border: 0;
        border-radius: 50%;
        position: absolute;
        transition: all 0.2s ease;
        -webkit-transition: background 0.2s;
        width: 10%;
        aspect-ratio: 1/1;
        max-height: 15%;
        cursor: pointer;
        z-index: 10;
        display: flex;
        justify-content: center;
        align-items: center;
        top: 50%;
        left: 50%;
        transform: translate3d(-50%, -50%, 0);
    }
    
    .wistia:hover button.embed-youtube__play,
    .wistia button.embed-youtube__play:focus-visible,
    .wistia button.embed-youtube__play:focus {
        background: url("https://nextiva.com/assets/svg/play-button.svg") no-repeat center center, #005fec;
        background-size: 40%;
        background-position: 55%;
    }
    
    .wistia_embed,
    .wistia embed,
    .wistia iframe {
        width: 100%;
        max-height: 100%;
    }
    
    .wistia_embed {
        display: none;
    }
    
    .wistia.shown .wistia_embed {
        display: block;
    }
    <div class="wistia">
        <picture>
            <source
                srcset="https://embedwistia-a.akamaihd.net/deliveries/48f1d62d1ceddb4284ad9cf67c916235.jpg?auto=format&w=640"
                media="(min-width: 1200px)">
            <source
                srcset="https://embedwistia-a.akamaihd.net/deliveries/48f1d62d1ceddb4284ad9cf67c916235.jpg?auto=format&w=310"
                media="(min-width: 768px)">
            <img src="https://embedwistia-a.akamaihd.net/deliveries/48f1d62d1ceddb4284ad9cf67c916235.jpg?auto=format&w=310"
                alt="some text" class="wistia__overlay lazy" loading="lazy">
        </picture>
        <div class="wistia_embed wistia_async_vhkqhqhzyq videoFoam=true"></div>
        <button class="embed-youtube__play"></button>
    </div>
    
    <div class="wistia">
        <picture>
            <source
                srcset="https://embed-fastly.wistia.com/deliveries/2eab84ad71cf5acd9c7572d36667d255.jpg?auto=format&w=640"
                media="(min-width: 1200px)">
            <source
                srcset="https://embed-fastly.wistia.com/deliveries/2eab84ad71cf5acd9c7572d36667d255.jpg?auto=format&w=310"
                media="(min-width: 768px)">
            <img src="https://embed-fastly.wistia.com/deliveries/2eab84ad71cf5acd9c7572d36667d255.jpg?auto=format&w=310"
                alt="Some text" class="wistia__overlay lazy" loading="lazy">
        </picture>
        <div class="wistia_embed wistia_async_8ei13wuby7 videoFoam=true"></div>
        <button class="embed-youtube__play"></button>
    </div>

    【讨论】:

    • 我明白你做了什么,但是当我点击播放视频时,之后我无法暂停视频。点击视频应该可以让我随意暂停,但它只是继续播放。
    • @Millhorn,你是对的。那是因为该事件在第一次点击后被触发一次又一次。检查更新的答案,如果这能解决您的问题,请告诉我。
    • 一切都很好。一切都正确实施到我的网站中。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2020-08-12
    • 2023-03-07
    • 1970-01-01
    • 2020-11-24
    • 2011-02-10
    • 2018-01-28
    • 2013-11-09
    • 1970-01-01
    相关资源
    最近更新 更多