【问题标题】:Imitating placeholder behaviour using JavaScript使用 JavaScript 模仿占位符行为
【发布时间】:2019-07-11 21:15:08
【问题描述】:

我正在尝试使用 javascript(和 jQuery)重新创建或模仿(HTML)占位符行为。

谁能告诉我如何实现这一目标? 我尝试使用以下代码:

$(document).ready(function () {
    //On init:
    var initPlaceholderTxt = $("p").text();

    //Execution:

    //Using this, placeholder will not display correct information, 
    //lacking a previous clicked character:
    $("#test").on("keydown", function (event) {
        var value = $(this).val();
        $("p").text(value);
    });

    /*
    //Core feature:
     $("#test").keyup(function() {
          var value = $( this ).val();
      if(value != null && value != "") {
                $("p").text(value);
      }
      else {
            $("p").text(initPlaceholderTxt);
      }
    });

    //Make characters appear more dynamically or faster:
    $("#test").keydown(function() {
          var value = $( this ).val();
          $("p").text(value);
    });
    */
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="test"></textarea>
<p>Placeholder text</p>
<textarea placeholder="example"></textarea>

JSFiddle

我得到了主要部分的工作,但我正在努力让它更有活力。当用户在定义了占位符的默认输入中键入内容时,按下一个键的那一刻,一个字符将出现在框中,并且占位符将消失。我当前的代码似乎不会发生最后一部分。

当我按下一个键时,占位符已经尝试在新字符添加到输入之前更改其文本值。

Most 会说解决这个问题的方法是使用keyup。然而,使用keyup 也有一个缺点,因为当按下一个键时,它不会使字符动态出现在球棒的右侧。请告诉我如何解决这个问题。

编辑: 底部文本区域是显示预期行为的示例。 段落元素的行为/行为应该类似于您在示例中看到的(任何)占位符文本。

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    当我按下一个键时,占位符已经尝试在新字符添加到输入之前更改其文本值。

    但是,使用 keyup 也有一个缺点,因为它不会让字符在按下某个键时动态显示在球棒的右侧。

    那为什么不同时使用keyupkeydown

    .on() 的第一个参数可以在空格分隔列表中使用多个事件。

    编辑

    底部文本区域是显示预期行为的示例。

    我使用添加/删除类编辑了我的演示,这使第二个 &lt;textarea&gt; 占位符变为灰色...注意我给了它一个 id ;)

    $(document).ready(function() {
      //On init:
      var initPlaceholderTxt = $("p").text();
      
      //Execution:
      $("#test").on("keyup keydown", function( event ) {  
        var value = $( this ).val();
        $("p").text(value); // Just for the testing, I assume...
        
        $("#mainTextArea").text(value).removeClass("placeholder");
        
        
        // Restore the placeholder if the input is empty
        if(value==""){
          $("p").text(initPlaceholderTxt); // Just for the testing, I assume...
          
          $("#mainTextArea").text(initPlaceholderTxt).addClass("placeholder");
          
        }
      });
    
    });
    .placeholder{
      color:grey;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <textarea id="test"></textarea>
    <p>Placeholder text</p>
    <textarea placeholder="example" id="mainTextArea"></textarea>

    没有&lt;p&gt; 元素和placeholder 属性的简单演示:

    $(document).ready(function() {
      //On init:
      var initPlaceholderTxt = "Placeholder text";
      $("#mainTextArea").text(initPlaceholderTxt).addClass("placeholder");
      
      //Execution:
      $("#test").on("keyup keydown", function( event ) {  
        var value = $( this ).val();    
        $("#mainTextArea").text(value).removeClass("placeholder");
        
        // Restore the placeholder if the input is empty
        if(value==""){
          $("#mainTextArea").text(initPlaceholderTxt).addClass("placeholder");
        }
      });
    
    });
    .placeholder{
      color:grey;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <textarea id="test"></textarea>
    <br>
    <textarea id="mainTextArea"></textarea>

    【讨论】:

    • 有没有办法让元素&lt;p&gt;Placeholder text&lt;/p&gt; 像提供的示例文本区域这样的默认输入元素内的占位符文本一样响应更改?因为从我现在看到的情况来看,在(第一个或)任何输入中输入一个字符后,它不会立即改变。我认为这与我正在寻找的非常接近。
    【解决方案2】:

    使用 attr 将动态值设置为占位符

    $("#ELEMENT").attr("placeholder","example");
    

    Code

    【讨论】:

    • 嗨 Sam,他不想使用占位符属性,这是问题的重点。
    【解决方案3】:

    希望这会像魅力一样发挥作用。谢谢。

      var initPlaceholderTxt = $("p").text();
      $("#test").on("keydown", function( event ) {
        var value = $( this ).val();
        $("p").text(value);
        $("#desc").text(value);
      });
    

    【讨论】:

    • #desc 有什么作用?你做了哪些改变?你能给我看一个工作的例子吗?
    • desc 是用于 textarea 的 id,因此请将代码 中的这一行替换为
    【解决方案4】:

    $(document).ready(function() {
      //On init:
      var initPlaceholderTxt = $("p").text();
      $('#test').val('Text here');
      $('#test').css('color','grey');
      //Execution:
      $('#test').one('keypress',function(){
      $('#test').val('');
      $('#test').css('color','black');
      })
      //Using this, placeholder will not display correct information, 
      //lacking a previous clicked character:
      $("#test").on("keyup", function( event ) {
       
      	var value = $( this ).val();
      	$("p").text(value);
      });
      
      /*
      //Core feature:
    	$("#test").keyup(function() {
      	var value = $( this ).val();
        if(value != null && value != "") {
      		$("p").text(value);
        }
        else {
        	$("p").text(initPlaceholderTxt);
        }
      });
      
      //Make characters appear more dynamically or faster:
      $("#test").keydown(function() {
      	var value = $( this ).val();
      	$("p").text(value);
      });
      */
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <textarea id="test"  value="text"></textarea>
    <p>Placeholder text</p>
    <textarea placeholder="example"></textarea>

    【讨论】:

      【解决方案5】:

      如果您不介意使用 jQuery UI,您可以利用 jQuery UI's position utility:

      这是一个一般性的想法(如果你想让它成为一个通用插件):

      • 我使用data-placeholder 属性作为该元素占位符的元素的选择器。
      • 在初始化期间,我将占位符文本保留在占位符数据originalText
      • 在初始化期间,我保留对 textareas 数据中占位符元素的引用 placeholder
      • 最后,我将实际占位符设为高度 0,并且不对指针事件做出反应,以使所有点击都命中实际文本区域

      	//On init:
        $('[data-placeholder]').each(function () {
        		var $parent = $($(this).attr('data-placeholder'));
            $(this).data('originalText', $(this).text());
            $(this).position({
            	of: $parent,
              my: 'top left',
              at: 'top left'
            });
            $parent.data('placeholder', $(this));
        	
        });
        
        //Execution:
        
        //Using this, placeholder will not display correct information, 
        //lacking a previous clicked character:
        $("#test").on("keyup", function( event ) {
        	if ($(this).data('placeholder') && $(this).val()) {
          	 $(this).data('placeholder').text('');
          } else {
          	 $(this).data('placeholder').text($(this).data('placeholder').data('originalText'));
          }  
        });
      [data-placeholder] {
          z-index: 0;
          pointer-events: none;
          height: 0;
          overflow: visible;
          color: rgba(0, 0, 0, 0.5);
      }
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
      <div>
        <textarea id="test"></textarea>
        <span data-placeholder="#test">Placeholder text</span>
      </div>
      <div>
        <textarea placeholder="example"></textarea>
      </div>

      【讨论】:

        【解决方案6】:

        试试这个。你应该检查输入值的长度。然后根据你的需要应用占位符

        添加更多事件输入键以提高准确性

        $(document).ready(function() {
          var initPlaceholderTxt = $("p");
        initPlaceholderTxt.text($(initPlaceholderTxt).attr('placeholder'))
          $("#test").on("keydown input keyup", function(event) {
            var value = $(this).val();
            if ($.trim(value)) {
              initPlaceholderTxt.text("")
            } else {
              initPlaceholderTxt.text($(initPlaceholderTxt).attr('placeholder'));
            }
          });
        
        });
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <textarea id="test"></textarea>
        <p placeholder="example"></p>
        <textarea placeholder="example"></textarea>

        【讨论】:

          【解决方案7】:

          我只是要添加 es6 javascript 版本,因为我真的希望几年后会需要它,因为 jQuery 将被遗弃。

          简而言之,这是一个接受 2 个参数的函数:您的输入元素和您想要赋予它的占位符,它将处理所有其余的含义:

          • 如果在模糊事件中为空,则重置为占位符
          • 在焦点上重置为空值
          • 使用占位符值对其进行初始化

          当然没有针对性能进行优化,但应该可以帮助您。

          const input = document.querySelector('input')
          
          
          const placeholderCustom = (input, placeholder) => {
            !input.value ? input.value = placeholder : ''
            
            input.addEventListener('focus', () => {
              input.value === placeholder ? input.value = '' : placeholder
            })
            
            input.addEventListener('blur', () => {
              input.value === '' ? input.value = placeholder : ''
            })
            
            
            input.addEventListener('input', () => {
              input.value === placeholder ? input.value = '' : ''
            })
            
            
          }
          
          placeholderCustom(input, 'That is your placeholder')
          &lt;input type="text"&gt;

          【讨论】:

            猜你喜欢
            • 2011-11-19
            • 2020-09-18
            • 2019-04-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-07-25
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多