반응형
텍스트가 넘친 경우 감지
이 질문에 이미 답변이 있습니다.
- HTML 요소의 콘텐츠가 5 개의 답변을 오버플로하는지 확인
텍스트가 넘쳤는지 어떻게 감지 할 수 있습니까? 예를 들어 다음 텍스트는 div 컨테이너가 허용하는 것보다 깁니다. 자바 스크립트에서 어떻게 감지 할 수 있습니까?
<div style="max-width: 100px; white-space:nowrap; overflow: hidden;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit
</div>
jQuery를 사용하는 경우 div의 너비를 scrollWidth와 비교해 볼 수 있습니다.
if ($('#div-id')[0].scrollWidth > $('#div-id').innerWidth()) {
//Text has over-flown
}
요소를 표시 하기 전에 텍스트가 맞는지 여부를 감지 할 수 있습니다 . 따라서 요소가 화면에 표시되지 않아도되는이 기능을 사용할 수 있습니다.
function textWidth(text, fontProp) {
var tag = document.createElement('div')
tag.style.position = 'absolute'
tag.style.left = '-99in'
tag.style.whiteSpace = 'nowrap'
tag.style.font = fontProp
tag.innerHTML = text
document.body.appendChild(tag)
var result = tag.clientWidth
document.body.removeChild(tag)
return result;
}
용법:
if (textWidth('Text', 'bold 13px Verdana') > elementWidth) {
...
}
텍스트가 오버플로되었는지 확인하기위한 jQuery 플러그인은 잘 작성되지 않았지만 작동한다고 가정 한대로 작동합니다. 나는 이것에 대해 작동하는 플러그인을 어디서도 찾지 못했기 때문에 이것을 게시합니다.
jQuery.fn.hasOverflown = function () {
var res;
var cont = $('<div>'+this.text()+'</div>').css("display", "table")
.css("z-index", "-1").css("position", "absolute")
.css("font-family", this.css("font-family"))
.css("font-size", this.css("font-size"))
.css("font-weight", this.css("font-weight")).appendTo('body');
res = (cont.width()>this.width());
cont.remove();
return res;
}
설명을 위해 div에가 있다고 가정 id="d"하면 다음을 수행 할 수 있습니다.
var d = document.getElementById('d'),
dWider;
d.style.maxWidth = '9999em';
d.style.overflow = 'visible';
dWider = d.offsetWidth > 100;
d.style.maxWidth = '100px';
d.style.overflow = 'hidden';
그런 다음 dWider텍스트가 오버플로되면 var 는 true가되고 그렇지 않으면 false가됩니다.
참고 URL : https://stackoverflow.com/questions/6406843/detect-if-text-has-overflown
반응형
'Program Club' 카테고리의 다른 글
| Bash의 if 블록에서 부울 변수를 평가하는 방법은 무엇입니까? (0) | 2020.10.09 |
|---|---|
| org.hibernate.MappingException : java.util.Set에 대한 유형을 판별 할 수 없습니다. (0) | 2020.10.09 |
| onclick이 실행되면 HREF를 비활성화하려면 어떻게해야합니까? (0) | 2020.10.09 |
| IntelliJ IDEA에서 사용 강조 표시 색상을 변경하는 방법 (0) | 2020.10.09 |
| Kotlin에서 변수 이름 앞의 Kotlin 별표 연산자 또는 스프레드 연산자 (0) | 2020.10.09 |