ABOUT ME

Today
Yesterday
Total
  • 실습 - 버튼클릭하면 배경색 바꾸기
    카테고리 없음 2023. 1. 20. 16:53

    1차시도

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<meta http-equiv="X-UA-Compatible" content="IE=edge">
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    	<title>Document</title>
    </head>
    <body>  
    	<li onclick="changeColor('green')">Green</li>
    	<li onclick="changeColor('orange')">Orange</li>
    	<li onclick="changeColor('purple')">Purple</li> 
    	
    <script>
    	let li = document.querySelector('li'); 
    	function changeColor(color){
    		document.li.style.backgroundColor = color; 
    	}     	
    </script>
    </body>
    </html>

    2차시도 

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<meta http-equiv="X-UA-Compatible" content="IE=edge">
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    	<title>Document</title>
    </head>
    <body>  
    	<li onclick="changeColor('green')">Green</li>
    	<li onclick="changeColor('orange')">Orange</li>
    	<li onclick="changeColor('purple')">Purple</li> 
    	
    <script>
    
    	function changeColor(color){
    		let li = document.querySelector('li'); 
    		li.style.backgroundColor = color;
    	}   
    	
    </script>
    </body>
    </html>

     

    해설풀이 

     

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<meta http-equiv="X-UA-Compatible" content="IE=edge">
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    	<title>Document</title>
    	<link rel="stylesheet" href="css/styles2.css">
    </head>
    <body>  
    	<ul>
    		<li><a href="#" onclick="changeColor('green')">Green</a></li>
    		<li><a href="#" onclick="changeColor('orange')">Orange</a></li>
    		<li><a href="#" onclick="changeColor('purple')">Purple</a></li>
    	</ul>  
    	<div id="result"></div> 	  
    	
    <script>  
    	function changeColor(color){
    		let result = document.querySelector('#result'); 
    		result.style.backgroundColor = color;
    	}    	
    </script>
    </body>
    </html>

    댓글

Designed by Tistory.