Frontend/JavaScript
21. JavaScript, style접근
개발개발빈이
2022. 6. 21. 19:11
○ 자바스트립트에서 스타일 접근
- 참고 : jQuery에서 스타일 접근
<div id="mydiv" style="position: relative;
top: 10px;
left: 20px;
width: 150px;
height: 70px;
background-color: darksalmon;">대한민국</div>
<input type="button" value="mydiv의 style속성" onclick="test1()">
<input type="button" value="mydiv의 style변경" onclick="test2()">
1) 순수 자바스크립트 접근 : document.getElementById("요소의 id").style
<script>
function test1(){
alert(document.getElementById("mydiv")); //[object HTMLDivElement]
alert(document.getElementById("mydiv").style); //[object CSSStyleDeclaration]
}//test1() end
</script>
- document.getElementById("요소의 id").style.스타일속성
<script>
function test1(){
alert(document.getElementById("mydiv").style.top); //10px
alert(document.getElementById("mydiv").style.left); //20px
alert(document.getElementById("mydiv").style.width); //150px
alert(document.getElementById("mydiv").style.height); //70px
alert(document.getElementById("mydiv").style.backgroundColor); //darksalmon
alert(document.getElementById("mydiv").style.position); //relative
}//test1() end
</script>
- 스타일에 접근해서 수정하기
<script>
function test2(){
document.getElementById("mydiv").style.top="100px";
document.getElementById("mydiv").style.left="150px";
document.getElementById("mydiv").style.width="400px";
document.getElementById("mydiv").style.height="300px";
document.getElementById("mydiv").style.backgroundColor="green";
document.getElementById("mydiv").style.position="absolute";
}//test2() end
</script>
2) jQuery에서 스타일 접근 : $("요소의 식별자").css() → 추천
<script>
function test1(){
$("#mydiv").css();
}//test1() end
</script>