JQuery中怎么设置class

JQuery中怎么设置class,第1张

JQuery中设置class相关的有如下三个方法:

$(selector).addClass()       // 向被选元素添加一个或多个类

$(selector).removeClass()    // 从被选元素删除一个或多个类

$(selector).toggleClass()    // 对被选元素进行添加/删除类的切换 *** 作

下面实例演示一下以上三个方法的用法:

创建Html元素

<div class="box">

<span>点击不同按钮后,观察效果:</span><br>

<div class="content">

<li>list-item-1</li>

<li>list-item-2</li>

<li>list-item-3</li>

<li>list-item-4</li>

<li>list-item-5</li>

</div>

<input type="button" class="btn1" value="偶数位置添加红色样式"><br>

<input type="button" class="btn2" value="交换红色、黑色样式"><br>

<input type="button" class="btn3" value="去除所有红色样式">

</div>

简单设置css样式

div.box{width:300pxheight:300pxpadding:10px 20pxborder:4px dashed #ccc}

div.box>span{color:#999font-style:italic}

div.content{width:250pxheight:100pxmargin:10px 0padding:5px 20pxborder:1px solid green}

input{margin:10px}

input[type='button']{width:200pxheight:35pxmargin:10pxborder:2px solid #ebbcbe}

.red{color:red}

编写jquery代码

$(function(){

$("input:button.btn1").click(function() {

$(".content li:odd").addClass('red')

})

$("input:button.btn2").click(function() {

$(".content li").toggleClass('red')

})

$("input:button.btn3").click(function() {

$(".content li").removeClass('red')

})

})

观察显示效果

初始样式

点击第一个按钮,给偶数位置的列表项目添加red类

点击第二个按钮,有red类的元素去除red类,没有的就加上red类

点击第三个按钮,删除所有的red类

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

1、首先,打开html编辑器,新建html文件,例如:index.html,并引入jquery。

2、在index.html中的<script>标签,输入jquery代码:$('input').css('width', '250px')。

3、浏览器运行index.html页面,此时输入框的css样式的宽度被成功设置250px。

Jquery 怎么只给点击的元素加个class?1:新建一个html文件,命名为test.html,用于讲解jquery如何实现追加元素的同时添加class属性。

2:在test.html文件内,使用p标签创建一行测试的内容,并创建两个空div标签。

3:在test.html文件内,使用button标签创建一个按钮,给button按钮绑定onclick点击事件,当按钮被点击时,执行addPp()函数。

4:在函数内,通过获得p标签对象,使用appendTo方法将p标签追加到div中。

5:在函数内,再使用addClass方法给p标签添加一个class属性。

6:在浏览器打开test.html文件,点击按钮,查看结果。


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

原文地址: http://outofmemory.cn/tougao/6042581.html

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

发表评论

登录后才能评论

评论列表(0条)

保存