HTML id 속성은 요소에 고유 식별자를 할당하여 해당 요소에 CSS 및 JavaScript를 적용하기 위해 해당 요소를 선택하는 데 사용됩니다. 단일 HTML 페이지에서 두 개의 요소가 동일한 ID를 가질 수 없습니다. Id는 octothorpe(#)로 시작합니다.
참고 − HTML5부터는 숫자로 시작하는 id를 지정할 수 있습니다.
id 속성 −
에 대한 예를 살펴보겠습니다.예시
<!DOCTYPE html>
<html>
<head>
<title>MouseEvent clientX</title>
<style>
* {
padding: 2px;
margin:5px;
}
form {
width:70%;
margin: 0 auto;
text-align: center;
}
#outer {
width:70%;
margin: 0 auto;
padding: 0;
text-align: center;
border:1px solid black;
height: 105px;
background-color: #28a745;
}
input[type="button"] {
border-radius: 10px;
}
#upper {
border-bottom: 1px solid black;
height: 40px;
margin: 0 0 15px 0;
background-color: #DC3545;
}
#lower {
border-top: 1px solid black;
height: 40px;
margin: 15px 0 0 0;
background-color: #DC3545;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>MouseEvent-clientX</legend>
<div id="outer">
<div id="upper"><h2>Danger</h2></div>
<div id="lower"><h2>Danger</h2></div>
</div>
<input type="button" id="start" value="Start" onclick="gameStart()">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById('divDisplay');
var gameDisplay = document.getElementById('outer');
function playGame(event) {
var x = event.clientX;
var y = event.clientY;
if(y > 95 && y < 110){
divDisplay.textContent = 'Keep Going!';
if(x === 439){
divDisplay.textContent = 'Congrats! You Did it!';
gameDisplay.removeEventListener('mousemove', playGame);
}
} else {
divDisplay.textContent = 'You moved to DANGER area. You loose!';
gameDisplay.removeEventListener('mousemove', playGame);
}
}
function gameStart(){
gameDisplay.addEventListener('mousemove',playGame);
}
</script>
</body>
</html> 이것은 다음과 같은 출력을 생성합니다 -
1) '시작 클릭 후 ' 버튼과 커서가 녹색(안전) 영역에 있음 -

2) '시작 클릭 후 ' 버튼과 녹색(안전) 영역 끝의 커서 -

3) '시작 클릭 후 ' 버튼과 빨간색(위험) 영역의 커서 -
