使用jQuery调整窗口大小时更改占位符文本
使用jQuery,当用户在小型设备(~320px及更小)上时,如何将占位符文本更改为textarea? 我希望它更改为“回复…”用于小屏幕,但是大于320px的任何内容,它都会恢复为“回复[名称] …”
目前,我的HTML:
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');
您网页上的多个问题
并且您的选择器正在选择id属性
$('#my_textarea')
应该是
$('.my_textarea')
您可以使用$.each
迭代所有元素并相应地设置它们。
接下来,每个textarea
具有不同的占位符值。 所以现在是HTML-5
data- *属性的时候了。
HTML
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 );
使用数组保存初始值,然后迭代数组。
var placeholderValues = []; function changePlaceholder() { if( $(window).width() < 320 ){ $('.my_textarea').attr('placeholder','Reply...'); } else { $('.my_textarea').each(function(i){ $(this).attr('placeholder', placeholderValues[i]); }); } } // initiate first changePlaceholder(); //get values $('.my_textarea').each(function(){ placeholderValues.push($(this).attr('placeholder')); }); // resize $(window).resize( changePlaceholder );
演示: http : //jsfiddle.net/dirtyd77/CmaZg/
将旧占位符保存在数据属性中,然后在返回时将其还原
var shrunk = false; // Keep from repeating this when not necessary function changePlaceholder() { if(!shrunk && $(window).width() < 320){ $('.my_textarea').each(function() { $this = $(this); $this.data('save-placeholder', $this.attr('placeholder')) .attr('placeholder','Reply...'); }); shrunk = true; } else if (shrunk && $(window).width >= 320) { $('.my_textarea').each(function() { $this = $(this); $this.attr('placeholder', $this.data('save-placeholder')); }); shrunk = false; } }