addClass()和css()的区别

1、优先级css() > addClass()

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>测试</title>
		<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
	</head>
	<style>
		#one {
			width: 400px;
			height: 200px;
			background-color: #aaffff;
			text-align: center;
		}

		#two {
			margin-top: 10px;
			width: 400px;
			height: 200px;
			background-color: greenyellow;
			text-align: center;
		}
		.width-500{
			width: 500px;
			background-color: #000000;
		}
	</style>
	<body>
		<div id='one'><button >按钮</button></div>
		<div id='two'><button >按钮</button></div>
		<script>
			$(function(){
				$('#one button').click(function(){
					$('#one').addClass('width-500');
				})
				$('#two button').click(function(){
					$('#two').css('width','500');
					$('#two').css('background-color','#000000');
				})
			})
		</script>
	</body>
</html>

初始:
在这里插入图片描述
点击按钮后:
在这里插入图片描述
one没有变化,因为类选择器的优先级低于id选择器,解决办法是加上!important
在这里插入图片描述
而css()处理的是内联样式,直接通过元素的style属性附加到元素上的
在这里插入图片描述

2、css()不可保存旧值,addClass()可以通过removeClass()移除

		.width-500{
			width: 500px !important;
			background-color: #000000 !important;
		}
		$('#one button').click(function(){
					$('#one').toggleClass('width-500');
				})

点击按钮可设置/取消 width-500

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值