[英]How modify a property of external CSS file using jQuery / Javascript
I want to change a property of external CSS file using javascript/jquery
我想使用
javascript/jquery
更改外部CSS文件的属性
Example; 例; in the of the web page I'm using:
在我正在使用的网页中:
<!-- Star rating -->
<link href="css/star-rating.min.css" rel="stylesheet" />
And I want to access and change the color of specific style (Found in the external CSS): 我想访问和更改特定样式的颜色(在外部CSS中找到):
Exists a method using JavaScript or jQuery to do that? 存在使用JavaScript或jQuery执行此操作的方法?
I create a js method to achieve this: 我创建了一个js方法来实现这个目的:
function getStyleSheet(cssName, rule) {
for (i = 0; i < document.styleSheets.length; i++) {
if (document.styleSheets[i].href.toString().indexOf(cssName) != -1)
for (x = 0; x < document.styleSheets[i].rules.length; x++) {
if (document.styleSheets[i].rules[x].selectorText.toString().indexOf(rule) != -1)
return document.styleSheets[i].rules[x];
}
}
return null;
}
To change any property only is required the following: 要仅更改任何属性,需要以下内容:
getStyleSheet('star-rating', '.rating-container .rating-stars').style.color = "#AFAFAF";
Ok, let's analyze this.... 好吧,让我们分析一下....
You want to change a CSS rule on your code. 您想要更改代码上的CSS规则。 I asume you want to do it as a response to something that happens in the browser...
我想你想做它作为对浏览器中发生的事情的回应...
Change physically the line in the CSS file is not impossible, but I supose that it isn't what you are looking for. 物理上改变CSS文件中的行是不可能的,但我认为它不是你想要的。
The best option, probably would be to change the CSS style through javascript as a reaction to the event or situation that makes you want to change the style. 最好的选择,可能是通过javascript更改CSS样式,作为对您想要更改样式的事件或情况的反应。 Using jquery:
使用jquery:
$(".rating-container").css("color", "#f0f");
As an alternative, use different CSS classes for different element states and just change classes into your js code: 作为替代方案,对不同的元素状态使用不同的CSS类,只需将类更改为js代码:
$("#myAffectedElement").removeClass("oldColorClass");
$("#myAffectedElement").addClass("newColorClass");
This will allow you to modify directly individual elements styles instead of changing every originally classed element. 这将允许您直接修改单个元素样式,而不是更改每个原始的分类元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.