[실습문제02_DOM 조작]
- 문제1, 2 다 네모 검은 박스는 div로. 100x100 픽셀임.
- 색상 선택하는 input요소
ㅁ 문제 2-1
(1) 나
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="box1" style="width: 100px; height: 100px; background-color: black;"></div>
<input type="color">
<button onclick="fnChangeColor();">변경</button>
<script>
function fnChangeColor() {
const aa = document.getElementById("box1");
var col = document.getElementsByTagName("input");
aa.style.backgroundColor = col[0].value;
}
</script>
</body>
</html>
- property로 접근할 때는 background-color가 아니라 backgroundColor다.
- 태그로 요소를 선택할 때는 배열이다. !!
(2) 답
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>실습문제2</title>
<style>
div {
border: 1px solid black;
background-color: black;
height: 100px;
width: 100px;
}
</style>
</head>
<body>
<h3>문제 1. 색상 선택후 변경 버튼을 클릭하면 색상이 변경되도록 만들어 보시오</h3>
<div id="div1"></div>
<input type="color" id="selectColor">
<button onclick="changeColor();">변경</button>
<script>
function changeColor() {
const selectColor = document.getElementById("selectColor");
// 사용자가 색상을 선택하기 위한 input[type=color]요소 객체
const div1 = document.getElementById("div1");
// 색상을 반영시킬 div요소 객체
div1.style.backgroundColor = selectColor.value;
// div요소의 배경색상을 input[type=color]요소에 선택된 색상값(.value)으로 변경
// 위의코드를 한줄로 줄인다면 >>
document.getElementById("div1").style.backgroundColor = document.getElementById("selectColor").value;
}
</script>
</body>
- div에 인라인 방식으로 style 안주고 <head>의 <style>태그로 줬다.
- 속성 선택자로 표현하면 input[type=color] 이다.
ㅁ 문제 2-2
(1) 나
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="box2" style="width: 100px; height: 100px; background-color: black;"></div>
<button onclick="fn50x50();">50x50</button>
<button onclick="fn100x100();">원본(100x100)</button>
<button onclick="fn200x200();">200x200</button>
<script>
function fn50x50() {
const b = document.getElementById("box2");
b.style.width = "50px";
b.style.height = "50px";
}
function fn100x100() {
const b = document.getElementById("box2");
b.style.width = "100px";
b.style.height = "100px";
}
function fn200x200() {
const b = document.getElementById("box2");
b.style.width = "200px";
b.style.height = "200px";
}
</script>
</body>
</html>
(2) 답
[방법1]
<div id="div2"></div>
<button onclick="setHalfSize();">50x50</button>
<button onclick="setDefaultSize();">원본(100x100)</button>
<button onclick="setDoubleSize();">200x200</button>
<script>
// 전역변수로 div요소 가져다 두기 (어떤 함수든 다 사용할 수 있도록)
const div2 = document.getElementById("div2");
// 각 버튼 클릭시 마다 실행할 함수 따로 정의해두기
function setHalfSize(){
div2.style.width = '50px';
div2.style.height = '50px';
}
function setDefaultSize(){
div2.style.width = '100px';
div2.style.height = '100px';
}
function setDoubleSize(){
div2.style.width = '200px';
div2.style.height = '200px';
}
</script>
- div 요소 선택한 것을 <script> 태그 내에 전역변수로 뺐다.
<body>
[방법2. 위의 함수들을 하나로 통일해보기]
<div id="div2"></div>
<button onclick="sizeChange(50);">50x50</button>
<button onclick="sizeChange(100);">원본(100x100)</button>
<button onclick="sizeChange(200);">200x200</button>
<script>
function sizeChange(num){
const div2 = document.getElementById("div2");
div2.style.width = num + "px";
div2.style.height = num + "px";
}
</script>
</body>
- 함수에 매개변수를 선언해놓고 호출할 때 전달한 인자값을 써서 width, height 변경함.
[실습문제03_DOM 조작]
(1) 나
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>HTML 태그에 접근 테스트</h2>
<br><br>
<label for="consumer">구매자 :</label>
<input type="text" id="consumer" placeholder="구매자의 이름을 입력하세요." required> <br><br>
<label for="pName">상품명 :</label>
<input type="text" id="pName" placeholder="구매 상품명을 입력하세요." required> <br><br>
<label for="price">가격 :</label>
<input type="text" id="price" placeholder="구매 가격을 입력하세요." required> <br><br>
<button onclick="fnPrint();">입력값 출력하기</button> <br><br>
<textarea name="haha" id="a" cols="60" rows="10" style="resize:none; background-color:yellow;"></textarea>
<script>
function fnPrint() {
const outputArea = document.getElementById("a");
const consumerInput = document.getElementById("consumer");
const pNameInput = document.getElementById("pName");
const priceInput = document.getElementById("price");
outputArea.innerHTML = "구입자 : " + consumerInput.value
+ "님\n구입상품 : " + pNameInput.value
+ "\n구매가격 : " + priceInput.value + "만원";
}
</script>
</body>
</html>
- 인라인 방식으로 style줄 때 콜론으로 마무리한다.
- \n 자리에 원래 <br>을 썼는데 줄바꿈이 되지 않고 그대로 텍스트로 나왔다.
innerHTML이어도 textarea는 HTML태그가 안먹힌다.
※ textarea는 기본적으로 HTML 태그를 렌더링하지 않고 단순히 텍스트만 표시합니다.
줄 바꿈을 처리하기 위해, \n (줄 바꿈 문자)을 사용하여 텍스트를 포맷팅할 수 있습니다.
이 문자는 textarea에서 줄 바꿈을 표시하는 데 사용됩니다.
( 일반 HTML요소와 innerHTML에서 \n은 줄 바꿈을 생성하지 않으며, <br> 태그를 사용해야 합니다. )
(2) 답
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
#result {
width: 400px;
height: 150px;
background: #ffff99;
border: 1px solid #6666ff;
}
</style>
</head>
<body>
<h2>HTML 태그에 접근 테스트</h2>
구매자 : <input type="text" id="user" placeholder="구매자의 이름을 입력하세요."><br><br>
상품명 : <input type="text" id="productName" placeholder="구매 상품명을 입력하세요"><br><br>
가격 : <input type="text" id="productPrice" placeholder="구매 가격을 입력하세요."><br><br>
<button onclick="printValue();">입력값 출력하기</button><br><br>
<div id="result"></div>
<script>
function printValue() {
/* ----------------------------------------------------------
const userName = document.getElementById("user").value;
const productName = document.getElementById("productName").value;
const productPrice = document.getElementById("productPrice").value;
const result = document.getElementById("result");
result.innerHTML = "";
result.innerHTML += "구입자 : " + userName + "님<br>";
result.innerHTML += "구입상품 : " + productName + "<br>";
result.innerHTML += "구매가격 : " + productPrice + "만원";
------------------------------------------------------------*/
// 위의 소스코드들을 줄인다면
const result = document.getElementById("result");
result.innerHTML = "";
result.innerHTML += "구입자 : " + document.getElementById("user").value + "님<br>";
result.innerHTML += "구입상품 : " + document.getElementById("productName").value + "<br>";
result.innerHTML += "구매가격 : " + document.getElementById("productPrice").value + "만원";
}
</script>
</body>
</html>
- textarea가 아닌그냥 <div id="result"></div>를 썼다.
그리고 css의 style탭에서 result div를 꾸몄다.
그리고 div result를 선택해서 가져온 다음, innerHTML로 result에 사용자의 입력값을 출력했다. <br>태그 써서.
- <style> 태그의 type="text/css" 속성은 현대의 웹 표준에서는 필수가 아닙니다. HTML5에서는 <style> 태그 내의 CSS 코드를 자동으로 text/css로 처리하기 때문에, type 속성을 명시하지 않아도 CSS가 정상적으로 적용됩니다.
(그냥 <style></style>해도 정상 작동함)