如何将样式表添加到JSDOM [英] How do you add stylesheets to JSDOM

查看:97
本文介绍了如何将样式表添加到JSDOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在从事一个项目,该项目要求我将计算出的样式通过JSDOM发送到浏览器.我目前正在寻找一种将一些基本CSS注入JSDOM的方法,以便可以计算出正确的内联样式(是的,我知道那很不好).

I am currently working on a project that requires me to have computed styles send to the browser via JSDOM. I am currently looking for a way to inject some basic CSS into JSDOM so that it could compute the correct inline style (Yes I know that's bad).

从我发现的内容来看,我可以使用JSDOM 2级,但是从那里我找不到任何有关如何注入样式的文档.

From what I have found out I can use JSDOM Level 2, but from there I can't find any documentation on how to inject the styles.

这是我到目前为止所拥有的;

This is what I have so far;

    var document = jsdom.jsdom('<!DOCTYPE html><html><head></head><body id="abody" ></body></html>', jsdom.level(2, 'style'), {
        features : {
            FetchExternalResources : ['script', 'css'],
            QuerySelector : true
        }
    });

我一直在将css插入head标签,但无济于事.而且我知道我也可能在上面的代码中做错了.

I have been inserting the css into the head tag but to no avail. And I know I could be doing the above code wrong as well.

任何帮助都会很棒.

推荐答案

嗯,这听起来有点愚蠢,但这是我所做的:

Well, this is going to sounds kinda dumb but this is what I did:

    var path = require('path');
    var fs = require('fs');
    var mainCss = fs.readFileSync(path.normalize(__dirname + "web_main.css"), 'utf8');
    var document = jsdom.jsdom('<!DOCTYPE html><html><meta http-equiv="content-type" content="text/html; charset=utf-8"><head></head><body id="abody" ></body></html>', jsdom.level(3, 'index'), {
        features : {
            FetchExternalResources : ['script', 'css'],
            QuerySelector : true
        }
    });     
    var window = document.createWindow();
    var head = document.getElementsByTagName('head')[0];
    style = document.createElement("style");
    style.type = 'text/css';
    style.innerHTML = mainCss;
    head.appendChild(style);

所以基本上我所做的只是将级别移动到3索引,而不是直接在起始html中添加它,而是在其后附加了它.

So basically all I changed was moving the level to 3 index, and instead of directly having it in the starting html, I appended it afterwards.

它非常简单,我希望它可以帮助其他人.

Its pretty simple and I hope it helps someone else out.

这篇关于如何将样式表添加到JSDOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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