我正在尝试检索网页部分的当前内容(通常是div或table元素)。目标是将其显示为独立(例如用于打印目的)或将其插入另一页面。我不仅要收集元素,还要收集它们的计算样式,因为某些内容已被其他脚本突出显示或颜色编码。
我可以使用innerHTML获取html,并使用getComputedStyle获取特定元素的样式。但是我怎样才能获得整个部分的html和样式?
答案 0 :(得分:1)
我曾经在jQuery中做过一些可以检索所有(不是特定部分)样式的东西; .css文件,样式标签和特定页面的内部样式。我不知道该怎么做但也许你可以用某种方式使用这个脚本。它并不适用于所有场景,有时会出现一些小错误,因为我没有对它进行过足够的测试。 也许StackOverflow上还有其他人可以继续使用这段代码。 ;)
var all_css = {stylesheets:[], inner_head_styles:[], body_styles:[]};
$(function(){
$.ajaxSetup({
async: true,
crossDomain: true,
dataType: "text",
type: "GET"
});
var calls = [];
/*every non-cross-domain .css file*/
$("head link[rel='stylesheet']").each(function(a, stylesheet){
if($(stylesheet).attr("href").match(/((ftp|http|https):\/\/)?/)[0] == ""){
var css_source = $(stylesheet).attr("href");
var css_call = $.ajax({
url: css_source,
success: function(data){
all_css.stylesheets.push(data);
},
error: function(e, f){
alert(e, f);
}
});
calls.push(css_call);
}
else{
console.log("CSS SOLVER: Cross domain CSS's aren't going to be loaded!");
}
});
/*every head style*/
$("style").each(function(b, style){
all_css.inner_head_styles.push($(this).text());
});
/*every element in the body that has a style attribute*/
$("body[style], body *[style]").each(function(c, style){
var css_html_node = $(style).context.nodeName;
var css_class = typeof($(style).attr("class")) != "undefined" ? "."+$(style).attr("class") : "";
var css_id = typeof($(style).attr("id")) != "undefined" ? "#"+$(style).attr("id") : "";
css_class = css_class.replace(/\s/g, ".");
var css_string = css_html_node + css_id + css_class + "{" + $(style).attr("style") + "}";
all_css.body_styles.push(css_string);
});
$.when.apply(null, calls).done(function(){
console.log(all_css);
});
});
答案 1 :(得分:0)
您无法真正检索某个部分的样式,您必须在元素上获取样式。
您必须记住,您不再处理原始CSS,而是每个元素的计算样式。