jQuery修改DOM元素属性的操作
2019-12-25 本文已影响0人
讲武德的年轻人

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>jquery DOM操作</title>
<script src="js/jquery-1.12.4.js"></script>
<style type="text/css">
.button{
width:100px;
height:50px;
margin: 5px;
}
.up{
background-color: #F00;
border:#bbb solid 1px;
}
.down{
background-color: #FF0;
}
</style>
</head>
<body>
<input type="button" class="button up" value="Button" />
<script>
$('.button').click(function(e){
var $btn = $(e.target);
if($btn.hasClass('down')){
$btn.removeClass('down');
}else{
$btn.addClass('down');
}
});
</script>
</body>
</html>


更简单的代码如下,也能实现同样的效果:
<script>
$('.button').click(function(e){
$(e.target).toggleClass('down');
});
</script>