如何在JS中定义CSS

html-css013

如何在JS中定义CSS,第1张

var domObj = document.getElementById("tagId")

//使用domObj.style来设置css:

domObj.style.backgroundColor="#000"//对应style里 background-color

domObj.style.fontSize="#000"//对应style里 font-size

//如果对这个表不太清楚可以在w3c上查一下

//但是一般有个规律就是,首单词小写 “-”后面的第一个字母大写,如:font-size 就是fontSize

如果是想更换标签的class的话,可以使用

domObj.className = "other_class"

需要准备的材料分别有:电脑、html编辑器、浏览器。

1、首先,打开html编辑器,新建html文件,例如:index.html,编写问题基础代码。

2、在index.html中的<script>标签,输入js代码:$('div').click(function () {$(this).css('color', 'blue')})。

3、浏览器运行index.html页面,此时点击123所在的div,div会变为蓝色文本。

在页面内用JS操作CSS除非用AJAX,但操作页面内的样式的话,是可以的。操作样式分为改变直接样式,改变className和改变cssText三种

一、局部改变样式

调用方法:

改变className

<div id="demo">测试</div>

<script>

document.getElementById('demo').className="test"

</script>

改变直接样式

<div id="demo">测试</div>

<script>

document.getElementById('obj').style.backgroundColor="#003366"

</script>

二、全局改变样式

可以通过改变外链样式的的href的值实现网页样式的实时切换

<link rel = "stylesheet" type="text/css" id="css" href="firefox.css" />

<span on click="javascript:document.getElementById('css').href = 'ie.css'">点我改变样式</span>