新窗口中的外部样式表 [英] External stylsheets in new window

查看:122
本文介绍了新窗口中的外部样式表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:打开一个新窗口,插入元素,然后使用外部样式表将css样式应用到新窗口中的元素。

Goal: open a new window, insert elements, and then apply css style to the elements in the new window using an external style sheet.

问题:在新窗口中插入元素,获取新的窗口元素以使链接元素具有外部样式表,但新窗口元素不受样式表的影响。

Problem: I can insert the element in the new window, get the new window head element to have link elements to an external style sheet, but the new window elements are not being affected by the stylesheet.

小提琴
https://jsfiddle.net/1f2per3s/

Javascript

$('.button').on('click', function() {
  let win = window.open();

  let link = document.createElement('link');
  link.setAttribute('rel', 'stylesheet');
  link.setAttribute('type', 'text/css');
  link.setAttribute('href', '/stylesheets/my.css');
  win.document.head.appendChild(link);

  let div = document.createElement('div');
  div.innerHTML = '<div> hello world</div>';
  win.document.body.appendChild(div);
});

HTML

<div class="container">
  <div class="button">
    test element
  </div>
</div>


推荐答案

如果您在地址栏中查看,不在您的网站上(在Chrome中, about:blank )。

If you look in the address bar, the URL is not on your website (In Chrome, it's about:blank). The path to your stylesheet being relative, it is not found.

您可以使用完整的绝对网址来解决这个问题:

You can solve that by using the full, absolute URL:

link.setAttribute('href', 'http://example.org/stylesheets/my.css');

https://jsfiddle.net/3xhrnpsa/ (使用引导程序的CSS进行演示,使文本成为sans-serif)

https://jsfiddle.net/3xhrnpsa/ (using bootstrap's CSS for the demo, which makes the text sans-serif)

这篇关于新窗口中的外部样式表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆