JavaScript を使用して文字列の幅を計算したいと思います。等幅書体を使用しなくても、これは可能ですか?
組み込みでない場合、私の唯一の考えは、各文字の幅のテーブルを作成することですが、これは、特にUnicodeとさまざまなタイプのサイズ (およびその点ですべてのブラウザー) をサポートする場合にはかなり不合理です。
JavaScript を使用して文字列の幅を計算したいと思います。等幅書体を使用しなくても、これは可能ですか?
組み込みでない場合、私の唯一の考えは、各文字の幅のテーブルを作成することですが、これは、特にUnicodeとさまざまなタイプのサイズ (およびその点ですべてのブラウザー) をサポートする場合にはかなり不合理です。
次のスタイルでスタイル設定された DIV を作成します。JavaScript で、測定しようとしているフォント サイズと属性を設定し、文字列を DIV に配置してから、DIV の現在の幅と高さを読み取ります。コンテンツに合わせて伸縮し、サイズは文字列のレンダリング サイズの数ピクセル以内になります。
var fontSize = 12;
var test = document.getElementById("Test");
test.style.fontSize = fontSize;
var height = (test.clientHeight + 1) + "px";
var width = (test.clientWidth + 1) + "px"
console.log(height, width);
#Test
{
position: absolute;
visibility: hidden;
height: auto;
width: auto;
white-space: nowrap; /* Thanks to Herb Caudill comment */
}
<div id="Test">
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
</div>
これは、私が例を挙げずにまとめたものです。私たち全員が同じページにいるようです。
String.prototype.width = function(font) {
var f = font || '12px arial',
o = $('<div></div>')
.text(this)
.css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
.appendTo($('body')),
w = o.width();
o.remove();
return w;
}
使い方は簡単です:"a string".width()
**white-space: nowrapウィンドウ幅より大きい幅の文字列を計算できるように追加。
これは私のために働く...
// Handy JavaScript to measure the size taken to render the supplied text;
// you can supply additional style information too if you have it.
function measureText(pText, pFontSize, pStyle) {
var lDiv = document.createElement('div');
document.body.appendChild(lDiv);
if (pStyle != null) {
lDiv.style = pStyle;
}
lDiv.style.fontSize = "" + pFontSize + "px";
lDiv.style.position = "absolute";
lDiv.style.left = -1000;
lDiv.style.top = -1000;
lDiv.textContent = pText;
var lResult = {
width: lDiv.clientWidth,
height: lDiv.clientHeight
};
document.body.removeChild(lDiv);
lDiv = null;
return lResult;
}
jQuery:
(function($) {
$.textMetrics = function(el) {
var h = 0, w = 0;
var div = document.createElement('div');
document.body.appendChild(div);
$(div).css({
position: 'absolute',
left: -1000,
top: -1000,
display: 'none'
});
$(div).html($(el).html());
var styles = ['font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing'];
$(styles).each(function() {
var s = this.toString();
$(div).css(s, $(el).css(s));
});
h = $(div).outerHeight();
w = $(div).outerWidth();
$(div).remove();
var ret = {
height: h,
width: w
};
return ret;
}
})(jQuery);
ExtJS JavaScript ライブラリにはExt.util.TextMetrics という優れたクラスがあり、「テキスト ブロックの正確なピクセル測定値を提供するため、特定のテキスト ブロックの高さと幅をピクセル単位で正確に判断できます」。直接使用するか、ソースからコードを表示して、これがどのように行われるかを確認できます。
http://docs.sencha.com/extjs/6.5.3/modern/Ext.util.TextMetrics.html
そのための小さなツールを書きました。おそらくそれは誰かにとって有用です。jQuery なしで動作します。
https://github.com/schickling/calculate-size
使用法:
var size = calculateSize("Hello world!", {
font: 'Arial',
fontSize: '12px'
});
console.log(size.width); // 65
console.log(size.height); // 14
<span id="text">Text</span>
<script>
var textWidth = document.getElementById("text").offsetWidth;
</script>
<span> タグに他のスタイルが適用されていない限り、これは機能します。offsetWidth には、境界線の幅、水平パディング、垂直スクロールバーの幅などが含まれます。
キャンバスを使用できるため、css プロパティをあまり処理する必要はありません。
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.font = "20pt Arial"; // This can be set programmaticly from the element's font-style if desired
var textWidth = ctx.measureText($("#myElement").text()).width;
以下のコードスニップは、スパンタグの幅を「計算」し、長すぎる場合は「...」を追加し、親に収まるまで(またはそれ以上の試行が完了するまで)テキストの長さを短くします。千回)
CSS
div.places {
width : 100px;
}
div.places span {
white-space:nowrap;
overflow:hidden;
}
HTML
<div class="places">
<span>This is my house</span>
</div>
<div class="places">
<span>And my house are your house</span>
</div>
<div class="places">
<span>This placename is most certainly too wide to fit</span>
</div>
JavaScript(jQueryを使用)
// loops elements classed "places" and checks if their child "span" is too long to fit
$(".places").each(function (index, item) {
var obj = $(item).find("span");
if (obj.length) {
var placename = $(obj).text();
if ($(obj).width() > $(item).width() && placename.trim().length > 0) {
var limit = 0;
do {
limit++;
placename = placename.substring(0, placename.length - 1);
$(obj).text(placename + "...");
} while ($(obj).width() > $(item).width() && limit < 1000)
}
}
});
より良いのは、要素を表示する直前にテキストが収まるかどうかを検出することです。したがって、要素が画面上にある必要がないこの関数を使用できます。
function textWidth(text, fontProp) {
var tag = document.createElement("div");
tag.style.position = "absolute";
tag.style.left = "-999em";
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) {
...
}
このコードを試してください:
function GetTextRectToPixels(obj)
{
var tmpRect = obj.getBoundingClientRect();
obj.style.width = "auto";
obj.style.height = "auto";
var Ret = obj.getBoundingClientRect();
obj.style.width = (tmpRect.right - tmpRect.left).toString() + "px";
obj.style.height = (tmpRect.bottom - tmpRect.top).toString() + "px";
return Ret;
}
テキストの幅と高さは、 と で取得できますclientWidth。clientHeight
var element = document.getElementById ("mytext");
var width = element.clientWidth;
var height = element.clientHeight;
スタイル位置プロパティが絶対に設定されていることを確認してください
element.style.position = "absolute";
内にある必要はありません。またはdiv内にあることができますpspan
Deepak Nadar's answerに基づいて、関数のパラメーターを変更して、テキストとフォントのスタイルを受け入れるようにしました。要素を参照する必要はありません。また、fontOptionsデフォルトがあるため、すべてを指定する必要はありません。
(function($) {
$.format = function(format) {
return (function(format, args) {
return format.replace(/{(\d+)}/g, function(val, pos) {
return typeof args[pos] !== 'undefined' ? args[pos] : val;
});
}(format, [].slice.call(arguments, 1)));
};
$.measureText = function(html, fontOptions) {
fontOptions = $.extend({
fontSize: '1em',
fontStyle: 'normal',
fontWeight: 'normal',
fontFamily: 'arial'
}, fontOptions);
var $el = $('<div>', {
html: html,
css: {
position: 'absolute',
left: -1000,
top: -1000,
display: 'none'
}
}).appendTo('body');
$(fontOptions).each(function(index, option) {
$el.css(option, fontOptions[option]);
});
var h = $el.outerHeight(), w = $el.outerWidth();
$el.remove();
return { height: h, width: w };
};
}(jQuery));
var dimensions = $.measureText("Hello World!", { fontWeight: 'bold', fontFamily: 'arial' });
// Font Dimensions: 94px x 18px
$('body').append('<p>').text($.format('Font Dimensions: {0}px x {1}px', dimensions.width, dimensions.height));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
実際の例のフィドル: http://jsfiddle.net/tdpLdqpo/1/
HTML:
<h1 id="test1">
How wide is this text?
</h1>
<div id="result1"></div>
<hr/>
<p id="test2">
How wide is this text?
</p>
<div id="result2"></div>
<hr/>
<p id="test3">
How wide is this text?<br/><br/>
f sdfj f sdlfj lfj lsdk jflsjd fljsd flj sflj sldfj lsdfjlsdjkf sfjoifoewj flsdjfl jofjlgjdlsfjsdofjisdojfsdmfnnfoisjfoi ojfo dsjfo jdsofjsodnfo sjfoj ifjjfoewj fofew jfos fojo foew jofj s f j
</p>
<div id="result3"></div>
JavaScript コード:
function getTextWidth(text, font) {
var canvas = getTextWidth.canvas ||
(getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
};
$("#result1")
.text("answer: " +
getTextWidth(
$("#test1").text(),
$("#test1").css("font")) + " px");
$("#result2")
.text("answer: " +
getTextWidth(
$("#test2").text(),
$("#test2").css("font")) + " px");
$("#result3")
.text("answer: " +
getTextWidth(
$("#test3").text(),
$("#test3").css("font")) + " px");
jQuery を使用しない場合:
String.prototype.width = function (fontSize) {
var el,
f = fontSize + " px arial" || '12px arial';
el = document.createElement('div');
el.style.position = 'absolute';
el.style.float = "left";
el.style.whiteSpace = 'nowrap';
el.style.visibility = 'hidden';
el.style.font = f;
el.innerHTML = this;
el = document.body.appendChild(el);
w = el.offsetWidth;
el.parentNode.removeChild(el);
return w;
}
// Usage
"MyString".width(12);
これはデパックのエントリにかなり似ていると思いますが、印象的なウェブページの記事で公開されたルイス・ラザリスの作品に基づいています
(function($){
$.fn.autofit = function() {
var hiddenDiv = $(document.createElement('div')),
content = null;
hiddenDiv.css('display','none');
$('body').append(hiddenDiv);
$(this).bind('fit keyup keydown blur update focus',function () {
content = $(this).val();
content = content.replace(/\n/g, '<br>');
hiddenDiv.html(content);
$(this).css('width', hiddenDiv.width());
});
return this;
};
})(jQuery);
fit イベントは、関数がコントロールに関連付けられた直後に関数呼び出しを実行するために使用されます。
例: $('input').autofit().trigger("fit");
var textWidth = (function (el) {
el.style.position = 'absolute';
el.style.top = '-1000px';
document.body.appendChild(el);
return function (text) {
el.innerHTML = text;
return el.clientWidth;
};
})(document.createElement('div'));