使用 javascript 隐藏 iframe

Hide iframes using javascript

我正在尝试创建一个浏览器(我很无聊),我希望用户能够在选项卡之间导航。
这需要我隐藏一个 iframe 并显示另一个。我不确定如何使用 javascript 执行此操作。我也不希望 iframe 调整大小(比如说 height: 0px;)。

Here 是我的沙盒。

提前致谢。

将您的 iframe 包裹在 div 容器中,当您需要隐藏它时,只需添加样式或 class 并将其显示样式设置为 none

html

<div class="hide">

    <iframe></iframe>

</div>

css

.hide{
    display: none;
}

您可以动态添加自定义 CSS 到您的 iframe 以隐藏和显示。

参考以下代码,

<!DOCTYPE html>
<html>
<head>
<style>

.custom-style {
    width: 0; 
    height: 0; 
    position: absolute;
    border: 0;
}

</style>
</head>
<body>

    <iframe id="iframe"
    width="300" height="200" src="https://www.youtube.com/embed/zFZrkCIc2Oc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
    
   <br/>
    
    <button onclick="onHide();">Hide Me<button>
    
    <button onclick="onShow();">Show Me<button>
    

</body>

<script>

    function onHide() {
        document.getElementById('iframe').classList.add('custom-style');
    }
    
    function onShow() {
        document.getElementById('iframe').classList.remove('custom-style');
    
    }
 
</script>

</html>