如何在JS中定义CSS

html-css014

如何在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"

bj(){    var tobj=document.createElement('<style></style>')    document.insertBefore(tobj)    document.styleSheets[0].addRule(".caa","background: url('bg1.jpg') no-repeat scroll")    document.styleSheets[0].addRule(".cab","background: url('bg2.jpg') no-repeat scroll") } IE下有效,如果非IE浏览器,要将insertBefore换成其它方法.

通过js来改变CSS属性,使用jQuery可以很方便的实现,像这样:

$("img").css('border-color','red')

就可以把边框颜色都变成红色。

这是针对此问题的测试页面

2、这是3张图片

<img src='https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=975878983,2392470128&fm=11&gp=0.jpg'>

<img src='https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=61343736,951557457&fm=11&gp=0.jpg'>

<img src='https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1354592590,1762022981&fm=11&gp=0.jpg'>

3、这是图片的样式,边框默认为灰色。

img{

max-width:200px

border-color:gray

border-width:10px

border-style:solid

}

4、现在通过这几行用到jQuery的代码,控制图片边框根据鼠标移入移出边框变灰和变红。

$(function(){

$("img").on('mouseover',function(){

$(this).css('border-color','red')

}).on('mouseout',function(){

$(this).css('border-color','gray')

})

})

5、效果如图