티스토리 뷰

프로그래밍/Javascript

문자열의 width 구하기

메모하는습관 2011. 7. 29. 18:21

메시지 박스 같은 것을 만들다 보면 문자열의 길이가 일정하지 않다.

보통의 html tag들은 height는 내용에 따라 늘어나지만 width는 대부분 그렇지 않다.

그래서 문자열의 width를 구하는 방법을 생각해보던 중 그럴싸한 트릭을 생각해냈다.

 

우선 간단하게 설명을 하면

span tag는 문자열 만큼 width가 늘어나므로 span tag를 이용하여 문자열의 width를 구하면 된다.

1. span tagposition: absolute로 설정 한다.

2. span tag의 좌표를 화면에 보이지 않는 좌표로 잡는다 (예를 들면 top: -10000 또는 left: -10000)

3. 폰트와 같이 width에 영향을 미치는 style들도 감안한다.

4. span tag에 문자열을 넣는다.

5. span tagouterWidth 값을 받는다.

 

 

아래는 문자열의 width를 구하는 예제 이다.

 

 

아래는 위 sample의 코드 이다.

<script type="text/javascript">
function calcStrWidth() {
	$("#spanStrWidth").text($("#xstr").val());
	alert($("#spanStrWidth").outerWidth());
}
</script>
<span id="spanStrWidth" style="visibility:hidden; position:absolute; top:-10000; font-size:9pt;"></span>
<input id="xstr" style="width:200px; font-size:9pt; border:solid 1px #aaa" type="text" />
<button onclick="calcStrWidth()" style="font-size:9pt; border:solid 1px #aaa">문자열 width 구하기</button>
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday