Week2 - JavaScript (6)

김서하·2021년 5월 8일
0

Westudy

목록 보기
11/25
post-thumbnail

javascript이용하여 html/css에서 작성한 웹페이지의 내용 및 스타일 변경하기

참고 항목 - console.dir() :
지정된 **object**의 속성 목록을 대화형으로 표시
    console.dir(**wecode**);
    console.dir(**document**);
1 ) document.getElementById();

예1) document.getElementById("wecode");]
---> wecode = html에서 부여한 id값

const wecode = document.getElementById("wecode");
wecode.innerHTML = "Hi, this is H.";
wecode.style.color = 'red';
document.title = 'Change the title on JavaScript';
12) document.querySelector();

예2) document.querySelector(".study);]
---> study = html에서 부여한 class값

const study = document.querySelector(".study");
study.innerHTML = "Enjoy Coding";
study.style.color = 'green';

Events & Event Handlers

addEventListener(): 지정된 이벤트가 전달될 때마다 호출될 함수를 설정

1) Resize Event에 대한 console.log

function handleResize(){
     console.log("Window has been resized.");
}
window.addEventListener("resize", handleResize);

2) Click Event에 대한 style change

function handleclick(){
     wecode.style.color = 'blue';
}
wecode.addEventListener("click", handleclick);

if & else

if / else if / else 문의 구조

if( 확인하고 싶은 내용1 ){
   if문이 true일 때 block }
else if( 확인하고 싶은 내용2 ){
   if문이 false
   else if문이 true일 때 block }
else{
     block }
if(10===5){
     console.log("Hi!") }
else if(10===10){
     console.log("Nope!") }
else{
     console.log("false") }
**if/else응용**
   html에서 id/class 지정한 요소를
   javascript 내에서 click & mouseenter 시 
   color가 바뀌도록 if 구문을 포함한 fuction 추가
// 1. html에서 지정한 요소 갖고오기 (id&class)
const id = document.querySelector("#id");
const class = document.querySelector(".class");
// 2 . 바뀔 색상 먼저 지정
const COLOR1 = "yellow";
const COLOR2 = "red";
// 3-1. function에 if문 (click)을 추가
function handleclick(){
    if(id.style.color === COLOR1){
        id.style.color = COLOR2;
    } else {
        id.style.color = COLOR1;
    }
}
// 3-2. function에 if문 (mouseenter)을 추가
function handlemouse(){
     if(class.style.color === COLOR1){
         class.style.color = COLOR2
     } else {
         class.style.color = COLOR1
     }
 }
// 4. "Event" 발생 시 실행될 function 정리
id.addEventListener("click", handleclick);
class.addEventListener("mouseenter", handlemouse);
profile
개발자 지망생 서하입니당

0개의 댓글