2024.01.25 37일차 수업: Java Script 기초(4)


JS에서 속성 읽기/쓰기

JS에서 대상 자식 요소들을 선택 할 때 firstChild, lastChild, childNodes[0] ...

HTML 속성

getAttribute('속성명')

해당 속성의 현재값을 반환한다.

setAttribute('속성명', '새로 지정할 값')

해당 속성에 새로운 값을 지정한다.

CSS 속성

window.getComputedStyle(대상요소).css속성

대상의 스타일(Css) 속성을 반환한다.

대상.style.css속성 = '새 값'

대상에 css 적용할 때

cover.style.backgroundColor = "#f00";

예제

<div id="wrapper">
    <div class="cover">
        <img src="img/animals/a.png" alt="" id="bigImg">
    </div>
    <ul class="animal">
        <li class="a01"><img src="img/animals/a01.png" alt=""></li>
        <li class="a02"><img src="img/animals/a02.png" alt=""></li>
        <li class="a03"><img src="img/animals/a03.png" alt=""></li>
        <li class="a04"><img src="img/animals/a04.png" alt=""></li>
        <li class="a05"><img src="img/animals/a05.png" alt=""></li>
        <li class="a06"><img src="img/animals/a06.png" alt=""></li>
    </ul>
</div>
<script>
    const animalsUl = document.querySelector('.animal');
    const animalsLi = document.querySelectorAll('.animal>li');
    const cover = document.querySelector('.cover');
    const bigImg = document.querySelector('#bigImg');
    animalsUl.addEventListener('click', (e)=>{
        let selected = e.target // 현재클릭된 li 저장
        tab(selected)
    })
    const tab = (selected) => {
        let bg = window.getComputedStyle(selected).backgroundColor;
        let srcValue = selected.firstChild.getAttribute('src');
        console.log(bg) // browser에서 사용하는 color-code로 들어오기 때문에 rgb로 들어온다.
        cover.style.backgroundColor = bg;
        bigImg.setAttribute('src', srcValue)
    }
</script>

JS에서 text 값 읽기/쓰기

// 이런 코드일 때, innerHTML, innerText, textContent 각각의 결과는??
<h1 style="color:red;">
  <span style="display: none;">2030-01-01</span>
  타이틀       태그
</h1> 

innerHTML

▪️ JS에서 Text 가져올때 대상.innerHTML;

대상 안의 html을 그대로 읽어서 가져온다.

▪️ JS에서 Text 적용할 때

대상.innerHTML = 값

innerText

▪️ JS에서 Text 가져올때 대상.innerText;

대상 안의 문자만 가져온다. 대상 안에 공백이 있으면 공백을 제거하고 문자만 가져온다.
css가 적용된 상태로 읽어온다.(컬러같은 속성을 가져오는 것 아님. display:none처리되어서 보이지 않는 문자는 안가져온다던가 그런 상태를 말하는 것임)

▪️ JS에서 Text 적용할 때

대상.innerText = 값

textContent

▪️ JS에서 Text 가져올때 대상.textContent;

대상안의 문자를 가져온다. 공백도 함께 가져오고, css는 적용되지 않은 상태로 읽어온다.
(html요소만 없애고 가져오는 것과 동일)

▪️ JS에서 Text 적용할 때

대상.textContent = 값


mouse Event

mouseover & mouseout : 부모와 자식 요소간에 공간이 있는 경우 떨림 발생
mouseenter & mouseleave : 부모와 자식 요소간에 공간이 있어도 안정적으로 이벤트 발생

마우스 이벤트 예제

<div id="box"></div>
<script>
	const body = document.querySelector('body');
	const box = document.querySelector('#box');
	document.addEventListener('mousemove', (e)=>{
		let mouseX = e.pageX;
		let mouseY = e.pageY;
		box.innerText = `마우스의 x 좌표는: ${mouseX}, 마우스의 y 좌표는: ${mouseY}`
	})
	// if mouseX < 500 - body: backgroundColor: red,
	// if mouseX > 500 - body: backgroundColor: yellow
	document.addEventListener('mousemove', (e)=>{
		let mouseX = e.pageX;
		let mouseY = e.pageY;
		box.innerText = `마우스의 x 좌표는: ${mouseX}, 마우스의 y 좌표는: ${mouseY}`
		if(mouseX < 500){
			body.style.backgroundColor = 'red';
		}
		else{
			body.style.backgroundColor = 'yellow';
		}
	})
</script>

key Event

실제로 입력되는 값 중요

  • keypress: 값이 입력되어야 이벤트가 발생하는 것
    입력되는 값이 없으면 keypress라는 이벤트는 동작하지 않는다.

물리적으로 누르는 값 중요

  • keydown: 키보드를 눌렀을 때 실행
  • keyup: 키보드에서 손을 떼었을 때 실행

e.keyCode: 더이상 사용 x (deprecated)
→ keydown, keyup 이벤트를 사용하면 대소문자 모두 같은 키코드 반환
→ keypress 이벤트를 사용하면 대소문자 서로 다른 키코드 반환

e.key: 그냥 그 키 자체의 값을 반환함

키 이벤트 예제

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
		.face{transition:all 0.25s;width: 290px;height: 290px;background: url(img/eventimg/face.png) no-repeat;border-radius: 50%;position: absolute;left:50%;top:50%;margin-left: -145px;margin-top: -145px}
    </style>
</head>
<body>
    <div  class="face" style="border: 5px solid lavenderblush"></div>   
    <script>
        const face = document.querySelector('.face');
        console.log(face.style.borderColor) // inline으로 작업
        face.style.borderColor = 'lavender' // inline으로 작업
        console.log(face.style.borderColor) // inline으로 작업
    console.log(face.style.width) // width는 못가져온다 -> 왜? : inline으로 적용된 Style이 아니니까. width는 내부스타일로 지정되어있다.

    let leftValue = window.getComputedStyle(face).left; // left: 50%이지만 결과는 '50%'로 나오는게 아니라 '50%'가 계산된 값이 나옴
    leftValue = parseInt(leftValue)
    let topValue = window.getComputedStyle(face).top;
    topValue = parseInt(topValue)
    console.log(leftValue, topValue)

    window.addEventListener('keydown', (e)=>{
        if(e.key == 'ArrowLeft'){
        leftValue -= 30;
        face.style.left = `${leftValue}px`
        }
        else if(e.key == 'ArrowRight'){
            leftValue += 30;
            face.style.left = `${leftValue}px`
        }
        else if(e.key == 'ArrowUp'){
            topValue -= 30;
            face.style.top = `${topValue}px`
        }
        else if(e.key == 'ArrowDown'){
            topValue += 30;
            face.style.top = `${topValue}px`
        }
    })
</script>
```

parseInt

parseInt : 소수점 떼고 정수로 반환

console.log(parseInt('123'));
// 123 (default base-10)
console.log(parseInt('077'));
// 77 (leading zeros are ignored)
console.log(parseInt('1.98887009'));
// 1 (decimal part is truncated)

0개의 댓글