如果样式表没有破坏相同的来源策略,我让这个插件可以做你想做的事。
你可以像这样使用它:
<link rel="stylesheet" href="..." data-wrapper="#mySelector" />
<style data-wrapper="#mySelector">
.ninja {
visibility: hidden;
}
</style>
并在初始化后再次:
$("link[rel='stylesheet']").addWrapperToStyle("#mySelector");
$("style").addWrapperToStyle("#mySelector");
(function($) {
var $styleSheet = $("<style type='text/css'/>").appendTo("head");
function getStyle( $element, callback ) {
callback($element.text());
}
function getLink( $element, callback ) {
$.get($element.attr("href"), function( style ) {
callback(style);
});
}
function appendStyle( style ) {
$styleSheet.text(function(i, text) {
return text + "\n" + style;
});
}
function wrapStyle( element, selector ) {
var $element = $(element);
if ( $element.is("style") ) {
getStyle( $element, callback );
} else {
getLink( $element, callback );
}
function callback( style ) {
if ( style ) {
style = ("" + style).replace(/([^}]+){/g, function(match) {
var matches = match.split(","),
i = 0,
len = matches.length;
for ( ; i < len; i++ ) {
matches[i] = selector + " " + $.trim(matches[i])
}
match = matches.join(",");
return match;
});
appendStyle(style);
$element.remove();
}
}
}
$(function() {
$("link[rel='stylesheet'][data-wrapper], style[data-wrapper]").each(function() {
wrapStyle( this, this.getAttribute("data-wrapper") );
});
});
$.fn.addWrapperToStyle = function( wrapper ) {
return this.each(function() {
wrapStyle(this, wrapper);
});
}
})(jQuery);
我不确定跨浏览器的兼容性。不过你可以试试...