Joh*_*ith 3 javascript css properties
我必须按名称访问CSS类,并且下面的代码有效。但是,如果我尝试hui["myclass"]或hui[".myclass"]代替hui[0]它找不到它。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
.myclass {
color: #00aa00;
}
</style>
<script type="text/javascript">
function change_class() {
var hui = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
hui[0].style["color"]="#ff0000"
}
</script>
</head>
<body>
<div class="myclass" onclick="change_class()">Some Text</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
编辑:我需要能够访问我在第一行中描述的内容,我不想访问页面上的各个元素,而是直接通过类名访问样式表。
所以你们都说我不能仅通过索引按类名访问样式表吗?
不,您不能通过选择器访问它们-这是一个简单的列表。您首先必须为其建立索引:
// assuming those are the right rules (ie from the right stylesheet)
var hui = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
var styleBySelector = {};
for (var i=0; i<hui.length; i++)
styleBySelector[hui[i].selectorText] = hui[i].style;
// now access the StyleDeclaration directly:
styleBySelector[".myclass"].color = "#ff0000";
Run Code Online (Sandbox Code Playgroud)
当然这不是万无一失的方法,有可能
.myClass, .myOtherClass而不是盲目地分配color属性,您首先应该检查声明的存在。
| 归档时间: |
|
| 查看次数: |
6028 次 |
| 最近记录: |