본문 바로가기
수업(국비지원)/JavaScript

[JavaScript] name 속성을 이용한 태그 선택, 마우스 이벤트(onmouseover, onmouseout)

by byeolsub 2023. 4. 18.
  • name 속성을 이용한 태그 선택 

📌 

<!DOCTYPE html>
<!-- src/main/webapp/20220922/javascript1.html -->
<html>
<head>
<meta charset="UTF-8">
<title>name 속성을 이용한 태그 선택</title>
<script type="text/javascript">
   function copyvalue() {
	   document.f1.num2.value = document.f1.num1.value
   }
   function sumall() {
	   let num = document.f2.num.value
	   let tot1=0,tot2=0,tot3=0
	   for (let i=1;i<=num;i++) {
		   tot1 += i
		   if(i%2==0) tot2 += i
		   else tot3 += i
	   }
	   document.f2.sum.value = tot1
	   document.f2.evensum.value = tot2
	   document.f2.oddsum.value = tot3
   }
</script>
</head>
<body>
<form name="f1">
<input type="text" name="num1">
<input type="text" name="num2">
<input type="button" value="복사" onclick="copyvalue()">
</form>
<hr>
<h2>입력된 숫자까지의 합계 구하기</h2>
<form name="f2">
 <input type="text" name="num">
 <input type="button" value="합계" onclick="sumall()"><br>
  전체 합계 : <input type="text" name="sum"><br>
  짝수 합계 : <input type="text" name="evensum"><br>
  홀수 합계 : <input type="text" name="oddsum"><br>
</form>
</body>
</html>

  • 마우스 이벤트(onmouseover, onmouseout)
javascript 인식되는 부분
  1. <script>...</script> : script 태그 내부
  2. onxxx="...." : 이벤트 처리 부분
     - onmouseover : 마우스의 커서가 영역 내부에 존재하는 경우
     - onmouseout : 마우스의 커서가 영역 내부에 존재하다가,
                    마우스 커서가 밖으로 나간 순간.
     - bgColor : css의 background-color 속성과 같은 값.
  3. <a href='javascript:...'>...</a> 
          : href 의 원래 기능인 다른 페이지로 이동을
            자바스크립트 문장 실행하도록 수정함.

 

📌

<!DOCTYPE html>
<!-- src/main/webapp/20220922/javascript2.html -->
<html>
<head>
<meta charset="UTF-8">
<title>마우스 이벤트 </title>
</head>
<body>

<a href="javascript:alert('마우스클릭금지')" 
   onmouseover='document.bgColor="red"'
   onmouseout='document.bgColor="white"'>
   마우스 커서가 이곳에 들어 오면 바탕색이 빨강색으로 
   벗어나면 흰색으로 변경됨
</a>   
</body>
</html>