
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>버튼을 클릭하면 색상이 나오는 것</title>
<link rel="stylesheet" href="css/02.css">
<script type="text/javascript" src="../../js/jquery-3.7.1.min.js"></script>
<script type="text/javascript" src="js/02.js"></script>
</head>
<body>
<div id="container">
<div id="btnsDiv"></div>
<div>
<div id="colorDiv"></div>
<div id="hangulDiv"></div>
</div>
</div>
</body>
</html>
JS
$(document).ready(function(){
const arr_btn = [{color:"red", hangul:"빨강"}
,{color:"orange", hangul:"주황"}
,{color:"yellow", hangul:"노랑"}
,{color:"green", hangul:"초록"}
,{color:"blue", hangul:"파랑"}
,{color:"navy", hangul:"남색"}
,{color:"purple", hangul:"보라"}
];
let html = `<span>버튼을 눌러보세요</span>`;
arr_btn.forEach(item => {
html += `<button type='button'>${item.color}</button>`;
})
$("div#btnsDiv").html(html);
$("div#container > div#btnsDiv > button").click(function(e){
const i = $("div#container > div#btnsDiv > button").index($(e.target));
const color = arr_btn[i].color;
$('div#colorDiv').css({'width':'150px','height':'150px','background-color':`${color}`});
$('div#hangulDiv').html(`${arr_btn[i].hangul}`);
$('div#hangulDiv').css({'color': `${color}`});
})
$("div#container > div#btnsDiv > button").eq(0).trigger('click');
})
CSS
@charset "UTF-8";
div#container {
width: 90%;
margin: 0 auto;
padding: 2%;
}
div#container > div#btnsDiv > span {
font-size: 20pt;
background-color: navy;
color: white;
margin-right: 60px;
}
div#container > div#btnsDiv > button {
font-size: 20pt;
width: 100px;
height: 50px;
margin-right: 20px;
}
div#container > div:nth-child(2) {
display: flex;
}
div#container > div:nth-child(2) > div {
border: solid 0px gray;
margin: 20px 20px 0 0;
}
div#container > div:nth-child(2) > div#hangulDiv {
font-size: 60pt;
margin-top: auto;
}
정리
- jQueryStudy -> 01_eventHandling -> chap06_addClass_removeClass_accordion_tab_SeatReservation -> 02_css_btnClick_color.html, 02.js, 02.css