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


当前回答

如果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;
...
...
  
});

其他回答

简而言之,没有。

您不能将CSS应用于iframe中加载的HTML,除非由于跨域资源限制,您可以控制iframe中加载的页面。

就像尤金说的,一种粗鄙的做事方式。我最终遵循他的代码,并链接到我的自定义Css页面。我的问题是,有了twitter的时间轴,你必须做一些回避twitter来覆盖他们的代码一点点。现在我们有一个滚动的时间轴与我们的css,即更大的字体,适当的行高和使滚动条隐藏的高度大于他们的限制。

var c = document.createElement('link');
setTimeout(frames[0].document.body.appendChild(c),500); // Mileage varies by connection. Bump 500 a bit higher if necessary

只要添加这个,一切都很好:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">

是的。看看另一个线程的细节: 如何将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">

您可以先检索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)); });

好运!