如何用jquery 控制css样式

html-css024

如何用jquery 控制css样式,第1张

//1、获取和设置样式

$("#tow").attr("class")//获取ID为tow的class属性

$("#two").attr("class","divClass")//设置Id为two的class属性。

//2、追加样式

$("#two").addClass("divClass2")//为ID为two的对象追加样式divClass2

//3、移除样式

$("#two").removeClass("divClass")//移除 ID为two的对象的class名为divClass的样式。

$(#two).removeClass("divClass divClass2")移除多个样式。

//4、切换类名

$("#two").toggleClass("anotherClass") //重复切换anotherClass样式

//5、判断是否含有某项样式

$("#two").hasClass("another")==$("#two").is(".another")

//6、获取css样式中的样式

$("div").css("color")// 设置color属性值. $(element).css(style)

//设置单个样式

$("div").css("color","red")

//7设置多个样式

$("div").css({fontSize:"30px",color:"red"})

$("div").css("height","30px")==$("div").height("30px")

$("div").css("width","30px")==$("div").height("30px")

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Document</title>

    <link rel="stylesheet" href="jqhover.css"><!--这里显示外链式样式-->

    <!--<style>这里显示是内嵌式样式,两种方式都可以在下面的jq代码中获取到背景定位的值

        a{ background-position: 0px 0px}

        a:hover{ background-position: 120px -20px}

    </style>-->

    <script src="jquery-1.8.0.min.js"></script><!--这里引入jq库,你在使用的时候记住修改路径-->

    <script>

    $(function(){

        var bgPosition = $('a')

        bgPosition.hover(function(){

            alert($(this).css('background-position'))

        },function(){

            alert('ok')

        })

    })

    </script>

</head>

<body>

    <a href="#">1111111111111</a>

</body>

</html>

jquery很灵活,有很多种方法,一楼写了一种了,我再举2种

$("#div_id").find("span").attr("class","css_id") 或

$("#div_id span,.css_id span").text()

下面是完整例子,你可以试试,把jquery的引用地址改成你本地的就可以了。

<html>

<head>

<style>

.css_id{ color:red}

</style>

<script type="text/javascript" src="D:\jquery.js"></script>

<script>

$(function(){

alert($("#div_id span,.css_id span").text())

alert($("#div_id").find("span").attr("class","css_id").text())

})

</script>

</head>

<body>

<div id="div_id">

<span class="css_id">123</span>

</div>

</body>

</html>