所以我有以下代码
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
document.styleSheets[0].cssRules[0].style.color="blue";
</script>
</head>
//etc.
基本上这段代码可以在 IE 和 Mozilla 中运行,但不能在 Chrome 中运行。实际上,当您运行 document.styleSheets[0].cssRules 时,它返回一个 CSSRulesList 对象(在 IE 和 Mozilla 中),但在 Chrome 中它返回 null。顺便说一句,对于嵌入式样式,这个对象似乎甚至在 Chrome 中也能工作。
那么这个功能实际上在 Chrome 中不可用吗?如果是这样,是否有 Chrome 替代方案可以让您使用 Javascript 处理外部样式表/文件?
最佳答案
另一种选择
document.styleSheets[0].rules[0].style.color = "blue";
此代码段可能有助于查看支持的集合。建议先使用cssRules集合,如果不支持再使用rules集合。
if (document.styleSheets[0].cssRules)
document.styleSheets[0].cssRules[0].style.color = "blue";
else if (document.styleSheets[0].rules)
document.styleSheets[0].rules[0].style.color = "blue";
编辑
下面的代码片段在 IE8、IE11、Firefox、Chrome、Safari 和 Opera 上按预期工作;在我的本地和生产服务器上;它也适用于 jsbin ;但它不适用于 js fiddle - 在上述任何浏览器上!
<!DOCTYPE>
<html>
<head>
<style type="text/css">
.panel {
background-color: #00ff00;
color: #ffffff;
width: 100px;
height: 100px;
font-size: 30px;
}
</style>
<script type="text/javascript">
window.onload = function(){
document.getElementById('button').onclick = function() {
if (document.styleSheets[0].cssRules)
document.styleSheets[0].cssRules[0].style.color = "black";
else if (document.styleSheets[0].rules)
document.styleSheets[0].rules[0].style.color = "black";
};
};
</script>
</head>
<body>
<div class="panel"><b>Text</b></div>
<input type="button" name="button" id="button" value="Change Color" />
</body>
</html>
如果我将 style 部分更改为此
<link rel="stylesheet" type="text/css" href="http://external-server/styles.css" />
上面的代码片段仅适用于 IE11。所以,这似乎是一个跨域策略问题,因为 Firefox 说 同源策略不允许读取位于 http://external-server/styles.css 的远程资源。这可以通过将资源移动到同一域或启用 CORS 来解决。
也许下面的代码片段可以解决这个问题
<style type="text/css">
@import url("http://external-domain/styles.css");
</style>
好吧,@import 提示 失败了!但是让我们检查从外部服务器接收到的 header
Remote Address: x.x.x.x:x
Request URL: http://www.external-domain.com/styles.css
Request Method: GET
Status Code: 200 OK
+[Request Headers] 10
-[Response Headers] 11
Accept-Ranges: bytes
Connection: Keep-Alive
Content-Encoding: gzip
Content-Length: 105
Content-Type: text/css
...
如我们所见,我们拥有样式,但无法访问或更改它们。 Chrome 和 Opera 在说
`Uncaught TypeError: Cannot set property 'color' of undefined`;
Firefox 的说法相同,但更详细
`TypeError: document.styleSheets[0].cssRules[0].style is undefined`
最后,连 IE11 也有同样的看法:)
`SCRIPT5007: Unable to set property 'color' of undefined or null reference.
File: css.html, Line: 30, Column: 4`
好吧,此时还有一件事需要考虑 - CORS要求?! IE 8+、Firefox 3.5+、Chrome 3+、Opera 12+、Safari 4+ 支持 CORS ...
<!DOCTYPE>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
// Access CSS hosted on external domain using CORS
// http://stackoverflow.com/users/1310701/hex494d49
//
window.onload = function(){
var xhr = CORSRequest("GET", "http://external-domain/styles.css");
if (!xhr){ // if CORS isn't supported
alert("Still using Lynx?");
return;
}
xhr.onload = function() {
var response = xhr.responseText;
appendCSS(response);
}
xhr.onerror = function() {
alert('Something went wrong!');
};
xhr.send();
document.getElementById('button').onclick = function() {
if (document.styleSheets[0].cssRules)
document.styleSheets[0].cssRules[0].style.color = "black";
else if (document.styleSheets[0].rules)
document.styleSheets[0].rules[0].style.color = "black";
};
};
var appendCSS = function(css){
var s = document.createElement('STYLE');
s.setAttribute('type', 'text/css');
if(s.styleSheet) // IE
s.styleSheet.cssText = css;
else // the rest of the world
s.appendChild(document.createTextNode(css));
document.getElementsByTagName('HEAD')[0].appendChild(s);
};
var CORSRequest = function(method, url){
var xhr = new XMLHttpRequest();
if("withCredentials" in xhr){ // Chrome, Firefox, Opera, Safari
xhr.open(method, url, true);
}else if(typeof XDomainRequest != "undefined"){ // IE
xhr = new XDomainRequest();
xhr.open(method, url);
}else{ // CORS isn't supported
xhr = null;
}
return xhr;
};
</script>
</head>
<body>
<div class="panel"><b>Text</b></div>
<input type="button" name="button" id="button" value="Change Color" />
</body>
</html>
就是这样,它有效!刚刚在 IE8、IE11、Firefox、Chrome、Opera 和 Safari 上测试过。但是......只有在网络服务器上启用了 Access-Control-Allow-Origin ,否则你会得到这样的错误
XMLHttpRequest 无法加载 http://external-domain/styles.css。请求的资源上不存在“Access-Control-Allow-Origin” header 。因此不允许访问 Origin 'null'。
在我的服务器上它没有启用所以我必须自己做。如果有人在共享主机上,这可能是个问题。
题外话: 如何在 Apache 上启用 Access-Control-Allow-Origin
首先,启用Apache Headers模块
ln -s /etc/apache2/mods-available/headers.load /etc/apache2/mods-enabled/headers.load
重启 Apache
/etc/init.d/apache2 restart
在 Apache 配置文件的 Directory 部分添加这些行
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
或将它们添加到 .htaccess 文件中。最后两个可以省略。如果您只想限制某人访问,请将上一行的“*”替换为“www.my-kitchen.com”。再次重启网络服务器,仅此而已。
关于javascript - 无法在谷歌浏览器中访问外部 CSS 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24472352/
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
我在MiniTest::Spec和Capybara中使用以下规范:find_field('Email').must_have_css('[autofocus]')检查名为“电子邮件”的字段是否具有autofocus属性。doc说如下:has_css?(path,options={})ChecksifagivenCSSselectorisonthepageorcurrentnode.据我了解,字段“Email”是一个节点,因此调用must_have_css绝对有效!我做错了什么? 最佳答案 通过JonasNicklas得到了答案:No
我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在
我有一大串格式化数据(例如JSON),我想使用Psychinruby同时保留格式转储到YAML。基本上,我希望JSON使用literalstyle出现在YAML中:---json:|{"page":1,"results":["item","another"],"total_pages":0}但是,当我使用YAML.dump时,它不使用文字样式。我得到这样的东西:---json:!"{\n\"page\":1,\n\"results\":[\n\"item\",\"another\"\n],\n\"total_pages\":0\n}\n"我如何告诉Psych以想要的样式转储标量?解
我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah
我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r
我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e
我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以
我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳