Javascript / jQuery에서 문자열의 픽셀 길이를 결정합니까?
jQuery / JavaScript에서 문자열의 픽셀 길이를 결정하는 방법이 있습니까?
범위에 텍스트를 래핑 하고 jquery width () 사용
HTML 캔버스에 사용되는 컨텍스트에는 글꼴 크기를 확인하는 방법이 내장되어 있습니다. 이 메서드는 TextMetrics
텍스트의 너비를 포함하는 width 속성을 가진 객체를 반환 합니다.
function getWidthOfText(txt, fontname, fontsize){
if(getWidthOfText.c === undefined){
getWidthOfText.c=document.createElement('canvas');
getWidthOfText.ctx=getWidthOfText.c.getContext('2d');
}
getWidthOfText.ctx.font = fontsize + ' ' + fontname;
return getWidthOfText.ctx.measureText(txt).width;
}
또는 다른 사용자가 제안한 것처럼 span
요소로 래핑 할 수 있습니다 .
function getWidthOfText(txt, fontname, fontsize){
if(getWidthOfText.e === undefined){
getWidthOfText.e = document.createElement('span');
getWidthOfText.e.style.display = "none";
document.body.appendChild(getWidthOfText.e);
}
getWidthOfText.e.style.fontSize = fontsize;
getWidthOfText.e.style.fontFamily = fontname;
getWidthOfText.e.innerText = txt;
return getWidthOfText.e.offsetWidth;
}
테스트 :
- 첫 번째 솔루션 (캔버스)- 테스트 됨 , 작동 중 (픽셀 단위로 반환)
- 두 번째 솔루션 (DOM)- 테스트 됨 , 작동 중 (픽셀 단위로 반환)
구현 차이로 인해 두 값이 약간 다른 값을 반환 할 수 있습니다.
성능 테스트 : 100 회 이상 평균 26788 개의 호출. 2014 년 말 Mac mini, 1.4GHz i5에서 테스트 됨
Safari, 버전 10.1.1 (12603.2.4) :
- 첫 번째 솔루션 : 26788 호출의 경우 33.92 밀리 초
- 두 번째 솔루션 : 26788 호출의 경우 67.94 밀리 초
Google Chrome, 버전 60.0.3112.90 :
- 첫 번째 솔루션 : 26788 호출의 경우 99.1963 밀리 초
- 두 번째 솔루션 : 26788 호출의 경우 307.4605 밀리 초
나는 당신이 단지 문자열을 할 수 있다고 믿지 않지만 <span>
올바른 속성 (크기, 글꼴 두께 등)을 가진 문자열을 안에 넣으면 ; 그런 다음 jQuery를 사용하여 범위의 너비를 가져올 수 있어야합니다.
<span id='string_span' style='font-weight: bold; font-size: 12'>Here is my string</span>
<script>
$('#string_span').width();
</script>
절대 위치 div에 넣은 다음 clientWidth를 사용하여 태그의 표시된 너비를 가져옵니다. 가시성을 "hidden"으로 설정하여 div를 숨길 수도 있습니다.
<div id="text" style="position:absolute;visibility:hidden" >This is some text</div>
<input type="button" onclick="getWidth()" value="Go" />
<script type="text/javascript" >
function getWidth() {
var width = document.getElementById("text").clientWidth;
alert(" Width :"+ width);
}
</script>
Based on vSync's answer, the pure javascript method is lightning fast for large amount of objects. Here is the Fiddle: https://jsfiddle.net/xeyq2d5r/8/
[1]: https://jsfiddle.net/xeyq2d5r/8/ "JSFiddle"
I received favorable tests for the 3rd method proposed, that uses the native javascript vs HTML Canvas
Google was pretty competive for option 1 and 3, 2 bombed.
FireFox 48:
Method 1 took 938.895 milliseconds.
Method 2 took 1536.355 milliseconds.
Method 3 took 135.91499999999996 milliseconds.
Edge 11 Method 1 took 4895.262839793865 milliseconds.
Method 2 took 6746.622271896686 milliseconds.
Method 3 took 1020.0315412885484 milliseconds.
Google Chrome: 52
Method 1 took 336.4399999999998 milliseconds.
Method 2 took 2271.71 milliseconds.
Method 3 took 333.30499999999984 milliseconds.
First replicate the location and styling of the text and then use Jquery width() function. This will make the measurements accurate. For example you have css styling with a selector of:
.style-head span
{
//Some style set
}
You would need to do this with Jquery already included above this script:
var measuringSpan = document.createElement("span");
measuringSpan.innerText = 'text to measure';
measuringSpan.style.display = 'none'; /*so you don't show that you are measuring*/
$('.style-head')[0].appendChild(measuringSpan);
var theWidthYouWant = $(measuringSpan).width();
Needless to say
theWidthYouWant
will hold the pixel length. Then remove the created elements after you are done or you will get several if this is done a several times. Or add an ID to reference instead.
If you use Snap.svg, the following works:
var tPaper = Snap(300, 300);
var tLabelText = tPaper.text(100, 100, "label text");
var tWidth = tLabelText.getBBox().width; // the width of the text in pixels.
tLabelText.attr({ x : 150 - (tWidth/2)}); // now it's centered in x
참고URL : https://stackoverflow.com/questions/2057682/determine-pixel-length-of-string-in-javascript-jquery
'developer tip' 카테고리의 다른 글
내 C # 프로그램의 패널 내에서 다른 응용 프로그램을 어떻게 실행할 수 있습니까? (0) | 2020.11.11 |
---|---|
Java HashMap keySet () 반복 순서가 일치합니까? (0) | 2020.11.11 |
Linux 용 예쁘고 기능이 풍부한 Git GUI (0) | 2020.11.11 |
JavaScript에서 양식 제출 캡처 (0) | 2020.11.11 |
Facebook 페이지의 피드를 내 웹 사이트에 삽입하는 방법 (0) | 2020.11.11 |