1

jQuery を使用して、ユーザーが小さなデバイス (~320px 以下) を使用している場合、プレースホルダー テキストをテキストエリアに変更するにはどうすればよいですか? 小さな画面の場合は「返信...」に変更したいのですが、320pxを超えると「[名前]に返信...」に戻ります

現在、私のHTML:

<textarea class="my_textarea" rows="1" type="text" placeholder="Reply to Joe..."></textarea>
<textarea class="my_textarea" rows="1" type="text" placeholder="Reply to Jane..."></textarea>

jQuery:

function changePlaceholder() {
    if( $(window).width() < 320 ){
        $('.my_textarea').attr('placeholder','Reply...');
    } else {
      // how do I change it back here if there are many textarea's on the page?
    }   
}

// initiate first
changePlaceholder();

// resize
$(window).resize( changePlaceholder );

元のプレースホルダーに戻すにはどうすればよいですか?

4

4 に答える 4

2

それらを取り戻すことができるように、最初にすべての異なるプレースホルダーを保存する必要があります。

$('.my_textarea').each(function() {
    $(this).data('placeholder', $(this).attr('placeholder'));
});

function changePlaceholder() {
    if( $(window).width() < 320 ){
        $('.my_textarea').attr('placeholder','Reply...');
    } else {
        $('.my_textarea').each(function() {
            $(this).attr('placeholder', $(this).data('placeholder'));
        });
    }   
}

$(window).resize( changePlaceholder ).trigger('resize');
于 2013-07-22T21:21:40.463 に答える
1

ページに複数の問題がある

<textarea class="my_textarea"

そして、セレクターはid 属性として選択しています

$('#my_textarea')

察するに

$('.my_textarea')

を使用$.eachして、すべての要素を反復処理し、それに応じて設定できます。

次に、それぞれtextareaに異なるプレースホルダー値があります。ですから、HTML-5data-* 属性の時です。

HTML

 <textarea class="my_textarea"
              rows="1" type="text" data-placeholder="Reply to Joe..."
              placeholder="Reply to Joe..."></textarea>

JS

function changePlaceholder() {
    var windowWidth = $(window).width();

    if(windowWidth < 320 ) {
        $('.my_textarea').attr('placeholder','Reply...');
    }
    else {
         $('.my_textarea').each(function() {
              var that = this;
              $(this).attr('placeholder', function(_, plc) {
                    return that.data('placeholder');
              });
         });
    }
}

// initiate first
changePlaceholder();

// resize
$(window).resize( changePlaceholder );
于 2013-07-22T21:15:21.073 に答える