如何用JS来改变CSS属性?

JavaScript08

如何用JS来改变CSS属性?,第1张

通过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、效果如图

1、当元素绑定class样式

hello

此时可以通过改变class,去修改元素样式:

document.getelementbyid("d1").classname="green"

2、当元素使用直接样式,即

hello

document.getelementbyid("d1").style.color="green"

js修改input的属性值方法如下:

<html>

<head>

<title>test </title>

<meta charset="utf-8">

</head>

<script language="JavaScript">   function setReadonly() {    

//document.getElementById("test").setAttribute("readOnly", true)

document.getElementById("test").readOnly=true

}    function readWrite() {        //document.getElementById("test").setAttribute("readOnly",

false)

document.getElementById("test").readOnly=false

}    

</script>

<body>

<form name="addform" id="addform" method="post" action="">

<input type="text" id="test" >

<input type="button"  value="只读" onclick="setReadonly()">

<input type="button"  value="读写" onclick="readWrite()">

</form>

</body>

</html>

JavaScript一种直译式脚本语言,是一种动态类型、弱类型、基于原型的语言,内置支持类型。它的解释器被称为JavaScript引擎,为浏览器的一部分,广泛用于客户端的脚本语言,最早是在HTML(标准通用标记语言下的一个应用)网页上使用,用来给HTML网页增加动态功能。