jQuery addClassメソッドで指定のCSSを追加する方法
環境
Windows 10 Home 64bit
jQuery 3.6.3
構文
1.ボタンのイベントの定義
$(“#ボタンのID名").click(function () {処理コード})
2.CSSのクラスを追加する
$(“.セレクタ名").addClass(“CSS名");
addClassメソッドで指定のCSSを追加しています。
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btnchk").click(function () {
$(".boxss").addClass("cssTestA");
});
});
</script>
<style>
.boxss {
width: 130px;
height: 80px;
border: 1px solid #000;
}
.cssTestA {
font-size: 14px;
background-color: lightblue;
}
</style>
</head>
<body>
<div class="boxss">tokyo oosaka</div><br>
<input type="button" id="btnchk" value="検証" />
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btnchk").click(function () {
$(".boxss").addClass("cssTestA");
});
});
</script>
<style>
.boxss {
width: 130px;
height: 80px;
border: 1px solid #000;
}
.cssTestA {
font-size: 14px;
background-color: lightblue;
}
</style>
</head>
<body>
<div class="boxss">tokyo oosaka</div><br>
<input type="button" id="btnchk" value="検証" />
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btnchk").click(function () { $(".boxss").addClass("cssTestA"); }); }); </script> <style> .boxss { width: 130px; height: 80px; border: 1px solid #000; } .cssTestA { font-size: 14px; background-color: lightblue; } </style> </head> <body> <div class="boxss">tokyo oosaka</div><br> <input type="button" id="btnchk" value="検証" /> </body> </html>
実行結果
「検証」ボタンを押下すると、CSSのクラス「boxss」を指定して背景色がlightblueになります。