繁体   English   中英

当该页面具有时,我想将 css 类动态添加到正文<iframe>并希望在没有时删除该类<iframe>在其他页面

[英]I want to add css class dynamically to body when that page has <iframe> and want to remove that class when no <iframe> in other pages

我想隐藏父网站的滚动条并仅显示 iframe 滚动条。 但是当我将溢出隐藏属性应用于 body 时,它将被全局应用,但我只想应用可用的页面。 我怎样才能做到这一点? 任何人都可以帮助我吗?

使用 JavaScript 来确定iframe元素的存在,然后相应地删除或添加 class 到body标记。 就是这样:

if(!document.querySelector('iframe')){
   document.querySelector('body').classList.add = "newClass";
} else{
   document.querySelector('body').classList.remove = "newClass"; //In case class was already added
}

希望这能解决您的问题。

要向正文添加/删除类,您可以编写如下 js 代码:

如果您使用 jQuery:

jQuery(document).ready(function ($) {
  if ( $('iframe').length ) {
    $(body).addClass('is-iframe');
  } else {
    $(body).removeClass('is-iframe');
  }
});

纯js:

window.addEventListener("load", function(event) {
  if ( document.querySelector('iframe') ){
    document.querySelector('body').classList.add('is-iframe')
  } else {
    document.querySelector('body').classList.remove('is-iframe')
  }
});

我认为您还可以为 body.is-iframe 和 iframe 元素设置一些样式:

body.is-iframe {
  position: relative;
  width: 100vw;
  height: 100vh;
}

body.is-iframe iframe {
  position: aboslute;
  width: 100%;
  height: 100%;
  overflow-y: auto;
}

我还没有测试这段代码,但我想它应该可以工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM