站内搜索

workerdance.com — Trusted craft, unfailing commitment
返回文章列表
前端

js控制css样式

本文写于 2015 年,文中涉及的软件版本可能已有变化,核心排查思路仍可参考。

方法一:

将css单独写在一个css文件中, 在js中通过className属性赋值

创建一个XXX.css文件, 内容如下:

.aDiv {
	display: block;
	border: 1px solid #aaa;
	z-index: 110;
	width: 250px;
	filter: alpha(opacity =   0);
	position: absolute;
	text-align: center;
	font-size: 20px;
	font-weight: bold;
	font-family: 微软雅黑,宋体,Arial, Helvetica, sans-serif;
	line-heigh: 30px;
	color: #555;
	padding: 35px 0;
}

js文件中调用时, 使用className属性进行赋值, 如下:

obj.className = “aDiv”;

这样, 就可以将aDiv这个class属性都赋给了obj对象

注意: 需要将css和这个js文件放到同一个目录下; 或者在jsp文件中, 将这两个文件都引入

<script type="text/javascript" src="js/XXX.js"></script>
<link rel="stylesheet" type="text/css" href="css/XXX.css">

方法二:

将css的属性逐一赋给js文件中的对象

setStyle = function(obj) {
	obj.style.top = document.body.clientHeight*0.7/2;
	obj.style.left = document.body.clientWidth*0.7/2;
	obj.style.display = "block";
	obj.style.border = "1px solid #aaa";
	obj.style.zIndex = 110;
	obj.style.width = "250px";
	obj.style.filter = "alpha(opacity = 0)";
	obj.style.position = "absolute";
	obj.style.textAlign = "center";
	obj.style.fontSize = "20px";
	obj.style.fontWeight =  "bold";
	obj.style.fontFamily = "微软雅黑,宋体,Arial, Helvetica, sans-serif";
	obj.style.lineHeigh = "30px";
	obj.style.color = "#555";
	obj.style.padding = "35px 0";
}

这里需要注意的是, 属性的写法略有不同, css中的样式有连字符(-)相隔, 而js中没有; 如: css中z-index, 对应的js中就是zIndex, css中的font-size, 对应js中就是fontSize; 之所以要将连字符去除, 是因为连字符在JavaScript中将被识别为减号

workerdance
workerdance

记录开发与运维中的实践和踩坑。