음악, 삶, 개발

요소의 style 값을 JS 에서 받아내기 : getComputedStyle 본문

개발 Web/Vue.js 공부방

요소의 style 값을 JS 에서 받아내기 : getComputedStyle

Lee_____ 2020. 12. 28. 03:38

< 참고자료 >

 

v3.vuejs.org/guide/composition-api-template-refs.html#template-refs

 


아래와 같이 div 와 .css 가 있다.

<div id="something"></div>
#something {

    width               : 100%;
    height              : 100%;
    background-color    : red;

}

이때 idgetComputedStyle 함수를 이용해 해당 요소의 현재 style 의 각 속성별 값을 알아낼수있다.

function getStyle(id, property) {

 return getComputedStyle(document.getElementById(id))[property]

}
console.log(getStyle('something', 'width'))             // 731.429px
console.log(getStyle('something', 'height'))            // 189.714px
console.log(getStyle('something', 'backgroundColor'))   // rgb(255, 0, 0)

하지만 위와 같이 id 를 사용하는 경우 unique 한 id 를 생성해야하는 수고가 있다.

Vue 에서는 ref 속성을 이용해, id 를 생성하지않고 요소를 가져와,

getComputedStyle 의 인자로 넘길수있다.

<template>

    <div ref="something"></div>

</template>

<script>

    import { onMounted, ref } from 'vue';

    export default {

        setup() {

            const something = ref(null)

            onMounted(() => {

                const bgColor = getComputedStyle(something.value).backgroundColor 

                console.log(bgColor) // rgb(255, 0, 0)

            })


            return { something }

        }
        
    }

</script>

이때 중요한것은, 반드시 something.value (ref 객체명뒤에 .value 를 뒤에 붙여아함) 를 

getComputedStyle 에 인자로 넘겨야함!

 

아래와 같이 함수를 만들어 쓰면 추후 사용하기 편리할것이다.

function getStyle(vueRef, propertyName) {

    return getComputedStyle(vueRef.value)[propertyName]

}

const something = ref(null)

getStyle(something, 'backgroundColor') // rgb(255, 0, 0)