3

私は現在持っています:

jquery

$(document).ready(function () { 
    $('.span-fix').each(function(){ /* Do this for each extended input */
        var wide = $(this).width(), /* create a variable that holds the width of the form */
            label = $(this).prev('.add-on').width(); /* create another variable that holds the width of the previous label */
        $(this).width( wide - label ); /* subtract the label width from the input width and apply it in px */
    });
});

html

<div class="input-prepend">
    <span class="add-on">Location</span>
    <input name="ctl00$ContentPlaceHolder1$tbLocation" type="text" id="tbLocation" class="span12 span-fix" placeholder="Location" style="width: 97.04668304668304%; ">
</div>

問題を示すフィドル:http://jsfiddle.net/SuguM/

ただし、これはの新しい幅を適用しますpx。流動的なレイアウトを使用しているため、これをパーセントにする必要があります。

px適用されたものをに変換する方法はあり%ますか?

4

4 に答える 4

2

実際、計算ではパディングを省略します。このコードはあなたを助けると思います。

編集 :

これはFirefoxのコードです:

$(document).ready(function () {
    $('.span-fix').each(function(){ /* Do this for each extended input */
        var label = $(this).prev('.add-on').outerWidth();
        /* create another variable that holds the width of the previous label */
        $(this).width( (1-(label + $(this).outerWidth() - $(this).width())/$(this).parent().width()) *100 + "%" );
    });
});

そしてこれはクロームのコードです:

$(document).ready(function () {
    $('.span-fix').each(function(){ /* Do this for each extended input */
        var label = $(this).prev('.add-on').outerWidth(); 
        /* create another variable that holds the width of the previous label */
        $(this).css("width", (1-(label)/$(this).parent().width()) *100 + "%" );
    });
});​

chromeの場合、width cssプロパティをチェックするときにwidthメソッドを使用する場合は、プロパティcssを設定する必要があります。プロパティ値は、計算された値と同じではありません。

ここにjsFiddleの例があります。

ここに、2つの実装を持つjsFiddleがあります。これで、ブラウザを検出する必要があります。

于 2012-09-11T16:18:40.637 に答える
0

これは親の幅を取り、パーセンテージを計算するだけです。

$(this).width((wide - label)/$(this).parent().width()*100+'%');
于 2012-09-11T03:41:53.883 に答える
0

私による以前の投稿に基づいています。

var getPercent = function(elem) {
    var elemName = elem.attr("id"),
        width = elem.width(),
        parentWidth = elem.offsetParent().width(),
        percent = Math.round(100 * width / parentWidth);
    return percent;
};
于 2012-09-12T08:08:55.507 に答える
-1

これにより、ドキュメント全体のパーセンテージが計算されます。

$(this).width((wide - label) * 100 / $(document).width()+'%');
于 2012-09-11T03:44:42.060 に答える