728x90
자바스크립트 이벤트 활용
실습
실습 1
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>실습1</title>
<style type="text/css">
#wrap {
display: flex;
}
#wrap > div {
width: 50px;
height: 50px;
margin: 10px;
cursor: pointer;
}
#a {
background-color: lightblue;
}
#b {
background-color: lightgreen;
}
#c {
background-color: lightyellow;
}
.click {
border-radius: 50%;
}
</style>
</head>
<body>
<div id="wrap">
<div id="a" onclick="test1(this)"></div>
<div id="b"></div>
<div id="c" onclick="test2()"></div>
</div>
<script type="text/javascript">
// 3
function test1(obj) {
obj.style.backgroundColor = 'pink';
}
// 4
function test2() {
var elem = document.getElementById('c');
elem.style.backgroundColor = 'red';
}
// 1
document.querySelector('#b').addEventListener('click', function() {
this.style.borderRadius = '50%';
});
// 2
/*
document.querySelector('#b').onclick = test;
function test() {
// 토글 방식
if (this.className == 'click') {
this.className = '';
}
else {
this.className = 'click'
}
}
*/
</script>
</body>
</html>
실습 2
- 1번째 목록
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>실습2</title>
<style>
input {
width: 50%;
}
#list > li {
margin: 5px;
}
</style>
</head>
<body>
<input type="text" placeholder="내용입력후 엔터">
<ul id="list">
<li>1번째 목록</li>
</ul>
<script type="text/javascript">
var obj = document.querySelector('input');
obj.onkeydown = function(event) {
if(event.keyCode == 13) {
var elem = document.createElement('li');
var msg = document.createTextNode(this.value);
elem.appendChild(msg);
document.getElementById('list').appendChild(elem);
}
}
</script>
</body>
</html>
GitHub
https://github.com/Qkrwnsgus0522/Web
728x90