1

プログレスバーを作ろうとしています。HTML は次のとおりです。

<div class="progress-bar" style="width:5%"></div>

DIV の背景をその幅に合わせてペイントしたい。たとえば、100 未満 (返される値は px) の場合は、赤で塗りつぶします。

私は次のことを試しました:

var currentWidth = $('.progress-bar').width();
if (currentWidth < 100) {
    $('.progress-bar').css('background-color','red');
}

これが JSFiddle のデモです。

しかし、それはそれを描いているわけではありません。

私は javascript と jquery の使用に慣れていないので、構文エラーまたは表示できない何かである可能性があると思います。誰かがそれを機能させる方法を教えてもらえますか?

前もって感謝します。

4

4 に答える 4

1

これは「手動」の進行状況バーで、ボタンをクリックして拡大すると、色とサイズがどのように変化するかを確認できます。ボタンを取り外してループに配置するだけで、同じことが自動的に行われます。

デモ

HTML

<div class="progress-bar"></div>
<input type="button" id="increase" value="Increase" />

CSS

.progress-bar {
    border: 1px solid black;
    width: 5px;
    height: 50px;
}

jQuery

$(document).on("click", "#increase", function () {
    var currentWidth = $('.progress-bar').width();
    currentWidth += 5;
    $('.progress-bar').css('width', currentWidth + 'px');
    if (currentWidth < 100) {
        $('.progress-bar').css('background-color', 'red');
    } else if (currentWidth < 200) {
        $('.progress-bar').css('background-color', 'yellow');
    } else {
        $('.progress-bar').css('background-color', 'green');
    }
});
于 2013-07-26T15:34:56.503 に答える
1

あなたのコードは問題ありません。唯一のことは指定することですheight

<div class="progress-bar" style="width:5%;height:5px"></div>

そして、あなたのjsは似ているはずです

$(function () {
    var currentWidth = $('.progress-bar').width();
    console.log(currentWidth);
    if (currentWidth < 100) {
        $('.progress-bar').css('background-color', 'red');
    }
});

フィドル

于 2013-07-26T15:16:45.443 に答える
0

あなたのコードは機能していますdocument.ready。結果を確認するには、コードを挿入し、div にテキストを挿入する必要があるかもしれません。また、jQuery が正常に組み込まれていることを確認してください。

ライブデモ

HTML

<div class="progress-bar" style="width:5%">123</div>

Javascript

$(document).ready(function(){
    var currentWidth = $('.progress-bar').width();
    if (currentWidth < 100) {
        $('.progress-bar').css('background-color','red');
    }
});
于 2013-07-26T15:13:01.123 に答える
0

インライン スタイルを使用しているため、div の style プロパティを使用して幅を % で取得できます

var currentWidth = $('.progress-bar')[0].style.width;
if (parseFloat(currentWidth, 10) < 100) {
    $('.progress-bar').css('background-color','red');
}

複数の場合

$('.progress-bar').each(function(){
    var currentWidth = this.style.width;
    if (parseFloat(currentWidth, 10) < 11) {
        $(this).css('background-color','red');
    }
});
于 2013-07-26T15:13:22.433 に答える