jQuery操作DOM,很重要的一部分就是操作元素样式。 操作class样式相关方法:
- 获取样式:
attr("class") - 设置样式:
attr("class","newclass") - 追加样式:
addClass("newclass") - 移除样式:
removeClass("newclass") - 切换样式:
toggleClass("newclass")——有该样式就移除,没有就添加 - 判断是否存在样式:
hasClass("newclass")
练习:实现开关灯效果。原理:切换body背景色为黑色/白色,同时调整文字颜色。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm15.aspx.cs" Inherits="WebApplication1.WebForm15" %>
<!DOCTYPE html>
<html xmlns="[http://www.w3.org/1999/xhtml](http://www.w3.org/1999/xhtml)">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="[http://libs.baidu.com/jquery/1.8.3/jquery.min.js](http://libs.baidu.com/jquery/1.8.3/jquery.min.js)"></script>
<style>
.newclass {
background-color: black;
color:white;
}
.cls {
color:green;
}
</style>
<script type="text/javascript">
function deal()
{
//alert($('#title').attr('class')); 返回undefined
//$('#title').attr('class','newclass'); //原来的cls 就被替换了
//$('#title').addClass('newclass');//追加样式
//$('#title').toggleClass('newclass');
$('body').toggleClass('newclass');
}
</script>
</head>
<body>
<div id="title" class="">北盟网校 免费的网络学习平台</div>
<input type="button" onclick="deal()" value="执行" />
</body>
</html>
Code language: HTML, XML (xml)
说明:点击按钮调用deal(),执行toggleClass切换body的newclass样式,实现开灯关灯。
修改了原css里
background-color:Background;的错误,改为black。
Previous: 作业练一练-表格隔行换色和表格的某些行高亮和改变颜色
Next: 实现输入框获得焦点的时候背景颜色高亮效果