シナリオ:
- ユーザーは、ButtonA に「thisisabutton」というテキストを入力します
- ユーザーは、ButtonB に「thisisalongerbutton」というテキストを入力します
- 両方のボタンは、テキストの長さに合わせてサイズが動的に調整されるため、2 つの異なるサイズになります。
- ButtonA を ButtonB と同じサイズにしたい (ButtonA よりも長いため、これによってサイズが決まります)。
Javascriptでこれを行うための最良のアプローチは何ですか?
シナリオ:
Javascriptでこれを行うための最良のアプローチは何ですか?
<button id="ButtonA" onChange="ResizeButtons();">Hello</button>
<button id="ButtonB" onChange="ResizeButtons();">Worlddddddddddddddd</button>
<script type="text/javascript">
function getWidth(element) {
return parseInt(window.getComputedStyle ? window.getComputedStyle(element,null).getPropertyValue("width") : element.currentStyle.width );
}
function ResizeButtons() {
var buttonA = document.getElementById("ButtonA");
var buttonB = document.getElementById("ButtonB");
buttonA.style.width = "auto";
buttonB.style.width = "auto";
var buttonAWidth = getWidth(buttonA);
var buttonBWidth = getWidth(buttonB);
var maxWidth = (buttonAWidth > buttonBWidth ? buttonAWidth: buttonBWidth) + "px";
buttonA.style.width = maxWidth;
buttonB.style.width = maxWidth;
}
</script>
1)クロスブラウザ。
2)計算前に要素を「自動」にリセットします。そうしないと、最初の文字が入力された後、要素のサイズが変更されることはありません。
buttonA3)とを取得した後にDOMに再アクセスすることを回避しbuttonBます。
4)各ボタンが変更されている間チェックします。
編集
ResizeButtons();ボタンのコンテンツを変更するために使用している入力にイベントを配置する必要がある場合があります。さらにResizeButtons()、コンテンツが変更された直後に、ボタンのコンテンツを変更する現在のスクリプト内で関数を実行するだけです。
<button id="ButtonA">Hello</button>
<button id="ButtonB" onChange="ResizeButtons();">Worlddddddddddddddd</button>
<script type="text/javascript">
function ResizeButtons()
{
var buttonAWidth = document.getElementById("ButtonA").style.width;
var buttonBWidth = document.getElementById("ButtonB").style.width;
var maxWidth = 0;
if (buttonAWidth >= buttonBWidth){
maxWidth = buttonAWidth;
}
else{
maxWidth = buttonBWidth;
}
document.getElementById("ButtonA").style.width = maxWidth;
document.getElementById("ButtonB").style.width = maxWidth;
}
</script>
この回答はjQueryを利用していますが、原則は上記の回答と同じで、真の要素幅を取得するための余分な手間がかかりません。必ずしも jQuery を使用する必要があると主張しているわけではありませんが、より簡潔な方法で解決策を示していると思います。
コード:
<label for="buttonName">Enter Button Name:</label><input id="buttonName">
<button id="createButton">Create Button</button>
<div id="buttons"></div>
<script type="text/javascript">
$('#createButton').button().click(function(){
var buttonName = $('#buttonName').val();
$('#buttonName').val("");
$('#buttons').append($('<button>'+buttonName+'</button>').button());
var widestButton = 0;
$('#buttons button').each(function(){
widestButton = Math.max($(this).width(), widestButton);
});
$('#buttons button').width(function(){
if ($(this).width() < widestButton)
$(this).width(widestButton);
});
});
</script>