fake element

김태완·2022년 11월 9일
0

프론트엔드

목록 보기
25/30

특정 엘리먼트가 2줄을 넘었을때 trigger를 해야하는 상황이 있다고 생각해보자.
이때, fake element를 사용하면 가능하다.

아래와 같은 박스가 있을때, 해당 박스가 2줄 이하이면 button이 자세히보기, 2줄이 넘어가면 button이 닫기로 바뀐다고 가정해보자.

<div>feqfqfqqffqwqwfqwfqffekjqhfqhfqkffeqqfkfㅇqfqkfq....</div>

css로 해당 박스를 hide처리 할 수는 있겠지만, 그걸 trigger로 이벤트를 발생시키는건 불가능하다.

이때 해당 박스의 높이가 2줄인지, 3줄인지를 비교하면된다. 그런데 line-clamp로 높이를 짤랐기 때문에 아무리 client-height로 잡는다한들 2줄만큼의 height가 잡힐것이다.

해결법


const str = "feqfqfqqffqwqwfqwfqffekjqhfqhfqkffeqqfkfㅇqfqkfq...."

<div class="fake">{str}</div>
<div class="twoLine">{str}</div>

<style>
	.fake{
    	position: fixed;
        left: -99999px;
    }
    .twoLine{
   		...
    	line-clamp: 2;
    }

</style>
<script>
	const fakeHeight = document.querySelector(".fake");
    const tweLineHeight = document.querySelector(".twoLine");
    
    if(fakeHeight === tweLineHeight) setState(false) // 2줄 이하
    if(fakeHeight > tweLineHeight) setState(true)// 2줄 초과
</script>
profile
프론트엔드개발

0개의 댓글