【问题标题】:Responsive placeholder text响应式占位符文本
【发布时间】:2017-12-18 09:04:16
【问题描述】:

我需要一个包含动态值的placeholder

<input type="text" placeholder="Search by Name, Order Number and Location" style="width: 300px" />

<input type="text" placeholder="Search by Name" style="width: 300px" />

我需要在输入字段中显示所有占位符文本。可以减小字体大小,但需要动态方式。

有什么想法吗?

【问题讨论】:

  • 我建议您编辑您的帖子,我已经阅读了 3 次,但我仍然无法理解它。因此,无论占位符中有什么文本,您都希望输入框保持相同的大小?如果是这样,为什么不指定宽度?
  • @Anthony'Runt'Cleaves 他希望占位符文本始终可见,无论输入宽度如何。

标签: javascript angularjs html css placeholder


【解决方案1】:

var step = 0.1;

setInterval(function() {
  // Loop over input elements
  $('input').each(function() {
    // Only change font-size if input value is empty (font-size should only affect placeholder)
    if ($(this).val() === '') {
      // Create clone
      $clone = $('<span></span>')
        .appendTo('body')
        .addClass('inputClone')
        .text($(this).attr('placeholder'));
      // Adjust font-size of clone
      var fontSize = $(this).css('font-size');
      do {
        fontSize = parseFloat($clone.css('font-size')) - step;
        $clone.css({
          'font-size': fontSize
        });
      } while ($clone.width() > $(this).width());
      // Maintain input field size
      $(this).css({
        "width": $(this).width() + "px",
        "height": $(this).height() + "px"
      });
      // Change input font-size
      $(this).animate({
        'font-size': fontSize
      });
      // Delete clone
      $clone.remove();
    } else {
      // Default input field back to normal
      $(this)
        .finish()
        .clearQueue()
        .attr('style', function(i, style) {
          // Remove inline style for font-size
          return style.replace(/font-size[^;]+;?/g, '');
        });
    }
  });
}, 100);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <table border="1">
    <tr>
      <td>Name:</td>
      <td>
        <input type="text" id="name1" placeholder="Search by Name, Order Number and Location" />
      </td>
    </tr>
    <tr>
      <td>Name:</td>
      <td>
        <input type="text" id="name2" placeholder="Search by Name"/>
      </td>
    </tr>
  </table>
</form>

创建另一个字段并附加它

【讨论】:

  • 没有完全显示文本。
  • @JaganC 是的,但他的方法可能是你会使用的。也就是说,1)将文本克隆到另一个元素中。 2) 计算其大小。 3)不断调整克隆的大小,直到它足够小。 4) 使用其font-size 更新输入元素。作为记录,我认为您的原始想法(调整占位符文本的大小)是不合理的。也许更好的方法是避免长占位符值?
  • @romellem 是的,我知道了,已经实施了这个解决方案,但是客户不同意这个解决方案。他想显示长占位符,无论它是什么大小。
猜你喜欢
  • 2016-02-18
  • 2017-02-26
  • 1970-01-01
  • 1970-01-01
  • 2020-07-08
  • 2019-11-20
  • 1970-01-01
  • 1970-01-01
  • 2014-09-15
相关资源
最近更新 更多