티스토리 뷰
메시지 박스 같은 것을 만들다 보면 문자열의 길이가 일정하지 않다.
보통의 html tag들은 height는 내용에 따라 늘어나지만 width는 대부분 그렇지 않다.
그래서 문자열의 width를 구하는 방법을 생각해보던 중 그럴싸한 트릭을 생각해냈다.
우선 간단하게 설명을 하면
span tag
는 문자열 만큼 width가 늘어나므로 span tag
를 이용하여 문자열의 width를 구하면 된다.
1. span tag
의 position: absolute
로 설정 한다.
2. span tag
의 좌표를 화면에 보이지 않는 좌표로 잡는다 (예를 들면 top: -10000
또는 left: -10000
)
3. 폰트와 같이 width에 영향을 미치는 style들도 감안한다.
4. span tag
에 문자열을 넣는다.
5. span tag
의 outerWidth
값을 받는다.
아래는 문자열의 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>
'프로그래밍 > Javascript' 카테고리의 다른 글
[IE] IE 버전별 javascript 또는 css 사용 방법 (0) | 2011.09.18 |
---|---|
google map api v3 (심플 버전) (0) | 2010.12.14 |
javascript google api 모음 (0) | 2010.12.13 |
event를 발생 시킨 object 알아 내기 (0) | 2010.05.14 |
Window 크기 구하기 (0) | 2010.04.21 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
Blog is powered by
Tistory / Designed by
Tistory