如何动态添加class样式

如何动态添加class样式,第1张

1

如果学WEB,w3school是一个非常有用的网站,总能找到你需要的东西。

2

如下图所示,这是w3school中对jquery属性 *** 作方法的介绍。

3

attr()可以设置和获取class属性。

设置:

$("img").attr("class","intro")

获取:

$("img").attr("class")

注:

attr()是将原有的class属性设置为新的class属性,不是在原来的基础上添加新的class属性。

4

那如果要在原来的class样式基础上添加新的样式要使用什么方法呢?

那就是addClass()方法。

5

addClass()可以添加一个或多个class属性。

添加一个class属性:

$("img").addClass("intro")

添加多个class属性:

$("img").addClass("intro1 intro2")//属性之间用空格分隔。

注:

当多class样式作用于一个元素上时,后添加的class样式会覆盖之前的。

6

示例:

$(document).ready(function(){ $("button").click(function(){$("p:first").addClass("intro1 intro2") })})

<style type="text/css">.intro1{font-size:120%color:red}.intro2{color:blue}</style>

<p>This is a paragraph.</p>

添加了两个class样式,后面的样式覆盖了之前的。所以字体显示是蓝色的。

引入jquery

然后给你要设置动画的对象增加或者删除css3动画的类就可以了。

如我这里用colorchange这个渐变类在css里面写好动画效果以后在js里面给对象添加上就可以实现动画了

<!DOCTYPE html>

<html>

<head lang="en">

    <meta charset="UTF-8">

    <title>Test</title>

    <style type="text/css">

        body{

            padding: 20px

            background-color:#FFF

        }

        .colorchange

        {

            animation:myfirst 5s

            -moz-animation:myfirst 5s /* Firefox */

            -webkit-animation:myfirst 5s /* Safari and Chrome */

            -o-animation:myfirst 5s /* Opera */

        }

 

        @keyframes myfirst

        {

            from {background:red}

            to {background:yellow}

        }

 

        @-moz-keyframes myfirst /* Firefox */

        {

            from {background:red}

            to {background:yellow}

        }

 

        @-webkit-keyframes myfirst /* Safari and Chrome */

        {

            from {background:red}

            to {background:yellow}

        }

 

        @-o-keyframes myfirst /* Opera */

        {

            from {background:red}

            to {background:yellow}

        }

        #main{

            width:100px

            height:100px

            background:red

        }

        #cgbt{

            width: 100px

            margin: 20px 0 0 0

            text-align: center

            cursor: pointer

        }

        #cgbt:hover{

            background-color: #2D93CA

        }

    </style>

</head>

<body>

<div id="main">

    我会变么?

</div>

<div id="cgbt">

    点我让上面的变颜色

</div>

<script src="jquery-3.2.1.min.js" type="application/javascript"></script>

<script>

    $(document).ready(function(){

        $("#cgbt").click(function(){

            $("#main").attr("class","colorchange")

        })

    })

</script>

</body>

</html>

var fb = $(".fws-b")

$(".org").hover(function(){

    fb.show()

},function(){

    fb.hide()

})


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11512089.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-16
下一篇 2023-05-16

发表评论

登录后才能评论

评论列表(0条)

保存