是否有可能改变一个div的风格,居住在一个iframe在页面上使用CSS只?


当前回答

显然,它可以通过jQuery完成:

$('iframe').load( function() {
    $('iframe').contents().find("head")
      .append($("<style type='text/css'>  .my-class{display:none;}  </style>"));
});

https://stackoverflow.com/a/13959836/1625795

其他回答

可能不是你想的那样。在CSS文件中iframe也必须<link>。如果它在不同的域上,你甚至不能用javascript做到这一点。

如果iframe来自另一个服务器,你会有类似的CORS错误:

Uncaught DOMException: Blocked a frame with origin "https://your-site.com" from accessing a cross-origin frame.

只有在你可以控制这两个页面的情况下,你才能使用https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage安全地发送这样的消息:

在你的主站(一个加载iframe的站点):

const iframe = document.querySelector('#frame-id');
iframe.contentWindow.postMessage(/*any variable or object here*/, 'https://iframe-site.example.com');

在iframe网站上:

// Called sometime after postMessage is called
window.addEventListener("message", (event) => {
  // Do we trust the sender of this message?
  if (event.origin !== "http://your-main-site.com")
    return;
...
...
  
});

您可以先检索iframe的内容,然后像往常一样对它们使用jQuery选择器。

$("#iframe-id").contents().find("img").attr("style","width:100%;height:100%")

$("#iframe-id").contents().find("img").addClass("fancy-zoom")

$("#iframe-id").contents().find("img").onclick(function(){ zoomit($(this)); });

好运!

从客户端不可能。一个javascript错误将被提出“错误:权限拒绝访问属性“文档””,因为Iframe不是你的域的一部分。 唯一的解决方案是从服务器端代码中获取页面并更改所需的CSS。

是的。看看另一个线程的细节: 如何将CSS应用到iframe?

const cssLink = document.createElement("link");
cssLink.href  = "style.css";  
cssLink.rel   = "stylesheet";  
cssLink.type  = "text/css";  
frames['frame1'].contentWindow.document.body.appendChild(cssLink); 
//     ^frame1 is the #id of the iframe: <iframe id="frame1">