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