首先是代码:
<style type="text/css">
.label1 {
font-weight: bold;
color: #006699;
}
</style>
<script type="text/javascript">
function test(k) {
document.getElementById(k).style = label1; <--this does not work
}
</script>
我想知道是否可以使用 .CSSclass 设置元素的样式(这是代码隐藏文件 (Default.aspx.cs) 中定义的标签)? p>
了解我可以应用 .style.color
来设置颜色等,但想先看看上面是否可行。
函数 test(k) 是从代码隐藏中调用的。经测试可以正常工作。
最佳答案
document.getElementById(k).style = label1; <--this does not work
没有理由这样做,你没有一个名为 label1
的 JavaScript 变量,并且您不通过分配给 .style
来应用类(尽管我明白你为什么会想到这样做)。
您的 CSS 定义了一个类。要为元素指定该类,请在 modern browsers 上使用 classList
:
document.getElementById(k).classList.add("label1");
对于 IE9 及更早版本等较旧的浏览器,请使用 className
,这是一个以空格分隔的类列表(如 HTML class
属性):
document.getElementById(k).className += " label1";
<小时/>
The function test(k) is called from code-behind.
只要确保 k
是元素的客户端 ID。 (我认为服务器控件上客户端 ID 的属性被创造性地命名为 ClientID
,但 ASP.Net 不是我的菜,如果这是错误的技术,我很抱歉。)
关于javascript - 在 ASPX 页面中设置 document.getElementById().style = .cssclass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33656527/