자바스크립트를 이용하여 css효과를 사용할 때의 inline방식과 class방식의 차이점을 알아보겠습니다.
1. inline방식의 자바스크립트 css효과
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
function changeColor(){
document.getElementById("changeText").style.color = "red"; //inline방식
}
</script>
</head>
<body>
<p id="changeText">클릭한 버튼의 색에따라 문장이 바뀝니다</p>
<p><button type="button" onclick="changeColor()">빨강</button></p>
</body>
</html>
document.getElementById("id").style.color = "변수"; 를 사용하면
위의 사진과 같이 style="color:red"로 inline형식의 css가 적용된 것을 확인할 수 있습니다.
inline방식의 css사용 시 여러가지의 style을 적용 할 때 중복된 문장을 여러번 사용해야하는 번거로움이 있습니다.
function changeColor(){
document.getElementById("changeText").style.color = "red"; //글자색을 바꾼다
document.getElementById("changeText").style.background = "blue"; //배경색을 바꾼다
document.getElementById("changeText").style.fontSize = "14"; //글자크기를바꾼다
}
2. class방식의 자바스크립트 css효과
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.txtStyle{color:red; background:blue; font-size:14px;}
</style>
<script type="text/javascript">
function changeColor(){
document.getElementById("changeText").className="txtStyle"; //class 방식
}
</script>
</head>
<body>
<p id="changeText">클릭한 버튼의 색에따라 문장이 바뀝니다</p>
<p><button type="button" onclick="changeColor('')">빨강</button></p>
</body>
</html>
위의작성된 코드처럼 class를이용하여 style을 적용하였을 경우 class하나만을 사용하여도 다양한 효과를 얻을 수 있습니다.
'JavaScript > 초급 JS' 카테고리의 다른 글
input type="range" 크롬에서 value 표시 (0) | 2018.02.06 |
---|---|
getElementById생략하기 (0) | 2018.01.29 |