javascript - 使用 jQuery 调整窗口大小时更改占位符文本

标签 javascript jquery

使用 jQuery,当用户使用小型设备(~320 像素或更小)时,如何将占位符文本更改为文本区域?我希望它针对小屏幕更改为“回复...”,但任何大于 320 像素的屏幕,它都会恢复为“回复 [name]...”

目前,我的 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 );

我怎样才能恢复到原来的占位符?

最佳答案

您需要先存储所有不同的占位符,以便您可以取回它们:

$('.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');

关于javascript - 使用 jQuery 调整窗口大小时更改占位符文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17797508/

相关文章:

javascript - 如何使用特定 id 删除元素

现有类的 javascript 验证

javascript - 切换显示时的过渡效果 :none - display:block

javascript - jQuery将点击事件绑定(bind)到每次页面刷新时数字不断增加的id

javascript - Node.js 类型错误 : Cannot call method 'write' of undefined

javascript - 迭代点击函数javascript

javascript - 如何检查以确保我的所有输入都是 :radio elements have a value?

javascript - 页面加载时隐藏 div 并在几秒钟后显示相同的内容

javascript - 如何将元素的 id 设置为变量?

jquery - 2 列 - 都滚动(左侧停止其内容)