获取正文标记样式属性内容

时间:2015-10-02 16:29:31

标签: javascript jquery html

我有一串HTML代码存储在变量

var contents = "<html><body style='background-color:red; background-attachment:fixed; margin:20px; display:block; background-size:cover;'></body></html>"

如何获取style属性中的内容或body标签中的任何其他属性?

编辑:对于下面的答案,在将字符串转换为元素时,将删除html和body标签。对不起,我刚刚意识到这一点,实际上需要从普通字符串中获取它。

4 个答案:

答案 0 :(得分:2)

您可以使用DOMParser();

var htmlString = "<html><body style='background-color:red; background-attachment:fixed; margin:20px; display:block; background-size:cover;'><p>test</p></body></html>"

var dp = new DOMParser();
var context = dp.parseFromString(htmlString, "text/html");

var $contextBody = $(context).find('body');
console.log($contextBody.attr('style'));

现代浏览器支持DOMParser,但您应在此处查看兼容性。 http://caniuse.com/#feat=xml-serializer

答案 1 :(得分:0)

如果你正在使用jQuery,你可以试试;

var css = $(body).prop('css');

或者如果你不是;

var css = document.body.getAttribute('css');

修改

啊,如果你想从你的变量中获取它,那会有些不同。你可能会有一些成功(未经测试);

var css = contentsHTML.find('body').prop('css');

答案 2 :(得分:0)

我会使用DOMParser

var parser = new DOMParser(),
    doc = parser.parseFromString(contents, "text/html"),
    style = doc.querySelector('body').getAttribute('style');

console.log(style);

演示 - &gt;的 http://jsfiddle.net/a2hua4ju/

jQuery剥离某些标签,并将样本字符串(或者类似,猜测仅用于演示目的)注入DOM并不是一个好主意。

答案 3 :(得分:-1)

您可以使用:
1-

var style = $('body').prop('style');

获取类型的对象:CSS2Properties。

2-

var style = $('body').attr('style');

获取包含style属性的所有内容的字符串。