0. 경마게임
- 이 코드는 HTML, CSS, JavaScript를 사용하여 간단한 경마게임 만들기
(1) HTML 부분
- "start"버튼: 사용자가 게임을 시작하는데 사용
- <div id="line">: 경주 말들이 이동하는 경주 트랙을 의미
- 각 말은 <img>요소로 표시. 각각 고유ID(h1,h2,h3,h4)
(2) CSS
- #line 스타일: 트랙의 가로 선을 그리기 위해 border-right 속성을 사용
(3) JavaScript
- start() 함수: start버튼을 클릭할때 호출. 경주 시작
setInterval()함수를 사용하여 gaming() 함수가 일정한 시간간격으로 호출
- gaming() 함수: 경주 말들을 이동시키는 로직
Math.random() 함수를 사용하여 말들의 랜덤한 이동 시뮬레이션
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
#line {
width: 800px;
border-right: 2px solid black;
}
</style>
<script>
var rank = [];
function start() {
document.getElementById("start").style.display = "none";
rank = [];
document.getElementById("h1").style.marginLeft = "0px";
document.getElementById("h2").style.marginLeft = "0px";
document.getElementById("h3").style.marginLeft = "0px";
document.getElementById("h4").style.marginLeft = "0px";
timeId = setInterval(gaming, 100);
}
function gaming() {
document.getElementById("h1").style.marginLeft =
parseInt(document.getElementById("h1").style.marginLeft) +
parseInt(Math.random() * 50) +
"px";
document.getElementById("h2").style.marginLeft =
parseInt(document.getElementById("h2").style.marginLeft) +
parseInt(Math.random() * 50) +
"px";
document.getElementById("h3").style.marginLeft =
parseInt(document.getElementById("h3").style.marginLeft) +
parseInt(Math.random() * 50) +
"px";
document.getElementById("h4").style.marginLeft =
parseInt(document.getElementById("h4").style.marginLeft) +
parseInt(Math.random() * 50) +
"px";
if (parseInt(document.getElementById("h1").style.marginLeft) > 800) {
document.getElementById("h1").style.marginLeft = "810px";
if (!rank.includes(1)) {
rank.push(1);
}
}
if (parseInt(document.getElementById("h2").style.marginLeft) > 800) {
document.getElementById("h2").style.marginLeft = "810px";
if (!rank.includes(2)) {
rank.push(2);
}
}
if (parseInt(document.getElementById("h3").style.marginLeft) > 800) {
document.getElementById("h3").style.marginLeft = "810px";
if (!rank.includes(3)) {
rank.push(3);
}
}
if (parseInt(document.getElementById("h4").style.marginLeft) > 800) {
document.getElementById("h4").style.marginLeft = "810px";
if (!rank.includes(4)) {
rank.push(4);
}
}
if (
parseInt(document.getElementById("h1").style.marginLeft) > 800 &&
parseInt(document.getElementById("h2").style.marginLeft) > 800 &&
parseInt(document.getElementById("h3").style.marginLeft) > 800 &&
parseInt(document.getElementById("h4").style.marginLeft) > 800
) {
clearInterval(timeId);
alert(rank);
document.getElementById("start").style.display = "inline";
}
}
</script>
</head>
<body>
<button
onclick="start()"
id="start"
border-radius="10px"
style="background-color: aqua"
>
start
</button>
<div id="line">
<br />
<img src="../images/말.JPG" id="h1" width="100px" height="100px" /><br />
<img src="../images/말.JPG" id="h2" width="100px" height="100px" /><br />
<img src="../images/말.JPG" id="h3" width="100px" height="100px" /><br />
<img src="../images/말.JPG" id="h4" width="100px" height="100px" /><br />
</div>
</body>
</html>
1. javascript CSS 추가
- classList: HTML 요소의 클래스를 조작하는 자바스크립트 객체
- 클래스는 CSS 스타일을 적용하거나 요소에 대한 다양한 동작을 트리거함.
- classList 객체를 사용하면 클래스를 동적으로 추가, 제거, 토글하여 웹페이지 상호작용성 향상
1. add(class1, class2)
- 클래스 목록에 하나 이상의 클래스를 추가함.
- 클래스의 요소가 존재하면 중복x
2. remove(class1, class2)
- 클래스 목록에서 하나 이상의 클래스를 삭제
- 클래스가 요소에 없어도 에러발생x
3. toggle(class, force)
- 클래스 토글. 즉, 클래스가 이미 요소에 있는 경우 제거하고 없는 경우 추가
- 두번째 매개변수 force를 사용하여 클래스를 강제 추가 또는 제거 가능
4. contains(class)
- 클래스가 요소에 있는지 확인
- 클래스가 요소에 있으면 true, 그렇지 않으면 false
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.myStyle1 {
width: 100%;
background-color: red;
color: white;
font-size: 25px;
display: block;
}
.myStyle2 {
width: 100%;
background-color: blue;
color: white;
font-size: 25px;
display: block;
}
.myStyle3 {
width: 100%;
background-color: green;
color: white;
font-size: 25px;
display: block;
}
div {
display: none;
}
</style>
<script>
window.onload = function () {
document.getElementById("b1").addEventListener("click", function () {
document.getElementById("d1").classList.toggle("myStyle1");
});
document.getElementById("b2").addEventListener("click", function () {
document.getElementById("d1").classList.add("myStyle2");
document.getElementById("d1").classList.add("myStyle3");
});
document.getElementById("b3").addEventListener("click", function () {
document.getElementById("d1").classList.remove("myStyle3");
});
};
</script>
</head>
<body>
<button id="b1">toggle</button>
<button id="b2" class="active">add</button>
<button id="b3">delete</button>
<div id="d1">DIV 태그</div>
</body>
</html>
- HTML 및 자바스크립트 코드는 버튼을 클릭할때 버튼의 활성상태를 토글하는 예제
(1) HTML 구조
- 페이지에는 여러개의 버튼이 존재함.
- 몇몇 버튼은 초기 상태에서 active 클래스를 가짐
(2) CSS 스타일
- 스타일 시트에서 버튼의 스타일 정의
- 초기 상태에서 active 클래스를 가진 버튼의 배경색이 검정색, 텍스트 색상 초록색
- 마우스를 버튼 위로(hover)올리면 버튼 배경색 검정, 텍스트색상 초록
(3) 자바스크립트
- window.onload 이벤트 핸들러는 페이지가 로드되면 실행
- 이 핸들러는 모든 버튼 요소를 가져와 각 버튼에 대한 클릭 이벤트 리스너를 추가
- 클릭이벤트 리스너는 클릭된 버튼을 강조표시. active 클래스를 해당 버튼에 추가. 다른버튼 active 제거
- this.classList.add("active"): 현재 클릭된 버튼에 active 클래스를 추가
- buttons[j].classList.remove("active"): 모든 버튼에서 active 클래스 제거
(4) 결과
- 페이지를 열면 초기 상태에서 "2"버튼이 active 클래스를 가짐.
- 다른 버튼을 클릭하면 해당 버튼 강조 표시. 나머지 버튼 active 클래스 제거되어 일반 스타일로 돌아감
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
button {
border: none;
padding: 10px 20px;
background-color: aqua;
cursor: pointer;
}
.active,
button:hover {
background-color: black;
color: green;
}
</style>
<script>
window.onload = function () {
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function () {
for (var j = 0; j < buttons.length; j++) {
buttons[j].classList.remove("active");
}
this.classList.add("active");
});
}
};
</script>
</head>
<body>
<button>1</button>
<button class="active">2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>7</button>
</body>
</html>
(1) classList가 아닌 className으로 만들기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
button {
border: none;
padding: 10px 20px;
background-color: aqua;
cursor: pointer;
}
.active,
button:hover {
background-color: black;
color: green;
}
</style>
<script>
window.onload = function () {
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function () {
var current = document.getElementsByClassName("active");
if (current.length > 0) {
current[0].className = current[0].className.remove("active", "");
}
this.className = "active";
});
}
};
</script>
</head>
<body>
<button>1</button>
<button class="bt active">2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>7</button>
</body>
</html>
3. 변수의 scope
- 자바스크립트에서 변수를 선언하는 방법은 var, let, const.
- 각각 다른변수 생명주기를 가짐.
(1) var변수 선언
- var을 사용하여 변수를 선언할때는 변수는 함수 범위를 가짐
- 함수 내에서 선언된 var변수는 함수가 종료할때까지 존재
- 함수 외부 접근x
function example() {
var x=10;
if(true) {
var y = 20;
}
console.log(x);
console.log(y);
}
(2) let 변수 선언
- let을 사용하여 변수를 선언할 때는 변수는 블록범위를 가짐
- 블록 내에서 선언된 let변수는 블록을 빠져나가면 파괴
- 블록 외부에서 접근할 수 없음.
function example() {
let x=10;
if(true) {
let y = 20;
}
console.log(x);
console.log(y);
}
(3) const 변수 선언
- const를 사용하여 변수를 선언할 때 변수 역시 블록범위를 가짐
- const 변수는 상수로 간주되어 재할당 불가능
- 선언과 동시에 초기화
function example() {
const x = 10;
if(true) {
const y = 20;
}
console.log(x);
console.log(y);
}
(4) 변수명만으로 선언
- 변수명 없이 변수를 선언하면 앞에 window.이 생략된 것처럼 인식되어 전역변수로 사용
a = 10;
function example() {
b = 20;
if(true) { c= 30; }
console.log(a);
console.log(b);
console.log(c);
}
console.log(a);
example()
console.log(window.a);
console.log(window.b);
console.log(window.c);
(5) (1)~(4) 정리
변수 선언 방법
var, let, const, 변수명만으로 변수선언
var: 함수 스코프 형태의 변수 선언
let: 블록 스코프 형태의 변수 선언
const: 블록 스코프 형태의 변수 선언
변수명만으로 선언: 전역변수선언
4. 슬라이더 만들기
+ 설명 +
1) HTML
- HTML 문서의 <head> 섹션에서 스크립트 파일 mySlider.js를 가져옴
- <body>내에서 mySlider라는 ID를 가진 div 요소 정의
- div 요소에는 이미지 목록을 나타내는 data-imglist 속성과 이미지를 표시하는 <img>요소
- "이전"과 "다음" 버튼을 가짐
2) JavaScript
- window.onload 이벤트 핸들러를 사용하여 HTML 문서가 로드될때 코드 실행
- data-imglist 속성에서 이미지 URL 목록을 가져와 sliderImgs 변수에 저장
- 이 이미지 목록은 배열로 저장. 배열의 각 항목은 이미지 파일 경로임
- "holder" ID를 가진 <img> 요소를 mySlider 변수 저장
- index 변수를 사용하여 현재 표시 중인 이미지의 인덱스 추적
- "이전", "다음" 링크에 대한 클릭 이벤트 리스너 추가
- 주석에는 w3schools 홈페이지에서 제공하는 슬라이드 쇼 예제를 참고하라는 주석이 있음.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="mySlider.js"></script>
</head>
<body>
<div
id="mySlider"
data-imglist="['../images/콜라.jpg', '../images/사이다.jpg', '../images/환타.jpg']"
>
<h1>내가만든 이미지 슬라이더</h1>
<img
src="../images/콜라.JPG"
id="holder"
width="200"
height="200"
/><br />
<a href="#" id="prev">이전</a>
<a href="#" id="next">다음</a>
</div>
</body>
</html>
window.onload = function () {
var sliderImgs = document
.getElementById("mySlider")
.getAttribute("data-imglist");
sliderImgs = eval(sliderImgs);
console.log(sliderImgs);
console.log(sliderImgs[0]);
var mySlider = document.getElementById("holder");
var index = 0;
document.getElementById("prev").addEventListener("click", function () {
if (index == 0) {
index = sliderImgs.length;
}
index = index - 1;
mySlider.src = sliderImgs[index];
return false;
});
document.getElementById("next").addEventListener("click", function () {
index = index + 1;
index = index % sliderImgs.length;
mySlider.src = sliderImgs[index];
});
};