首页 > 解决方案 > 即使使用错误的 if 语句,Onscroll 也会保持触发功能

问题描述

我正在使用 onscroll 调用我的函数来播放视频,但我只希望它只触发一次该函数。我什至为它设置了条件,所以它只会发生一次但它不起作用。有什么想法吗?(用三个=固定)

我还可以play() failed because the user didn't interact with the document first在新页面加载时进入我的登台站点。

window.onscroll = scrollfunc;

function scrollfunc() {
    if (document.getElementById("vidhero").style.display = "none") {
        document.getElementById("vidhero").style.display = "block";
        document.getElementById("vidhero").play();
    }
}
<html>
<body>

<h1>The video element</h1>

<video id="vidhero" width="320" height="240" style="display:none" src="https://www.w3schools.com/tags/movie.mp4">
  Your browser does not support the video tag.
</video>
<div style="height: 100vh"></div>


</body>
</html>

标签: javascript

解决方案


使用 === 进行比较

window.onscroll = scrollfunc;

function scrollfunc() {
    if (document.getElementById("vidhero").style.display === "none") {
        document.getElementById("vidhero").style.display = "block";
        document.getElementById("vidhero").play();
    }
}

推荐阅读