【问题标题】:Input inside of a button in IE and FF在 IE 和 FF 中的按钮内输入
【发布时间】:2016-05-05 04:25:35
【问题描述】:

我有一个 UI,允许用户更改按钮上的文本。当他们单击编辑图标时,它会将按钮文本放入文本输入中,他们可以在其中进行编辑,然后保存。现在,这在 Chrome 中运行良好,但在 IE11 和 Firefox 中不起作用,即使我停止传播事件也是如此。似乎该事件永远不会进入 IE11 和 Firefox 中的文本输入。

<button type='button'>
<input type='text' id='mybutton' />
</button>

https://jsfiddle.net/s0duxn5f/

有人对如何在 IE11 和 Firefox 中进行这项工作有任何建议吗?

【问题讨论】:

    标签: javascript jquery html firefox


    【解决方案1】:

    您所做的在 HTML 中是无效的。当您在按钮内声明任何内容时,它会覆盖其中的任何其他嵌入式控件。因此,您无法访问这些嵌套元素。如果您试图在单击按钮时专注于输入字段,您可以执行以下操作。

    $("button").click(function(e) {
        $('#mybutton').focus();
    });
    

    例如:https://jsfiddle.net/DinoMyte/s0duxn5f/1/

    对于原始问题,如果您想在单击按钮进行编辑时显示按钮文本,您将不得不尝试以下一些技巧:

     <button id="button" type='button'>Text
     </button>
     <script>    
    $(document).ready(function(){
        $("#button").click(function(e) {
            if($(this).find('input').length == 0)
               $(this).append("<input type='text' id='mybutton'/>");    
            $('#mybutton').val($("#button").text());  
            $('#mybutton').focus();
        });
    
        $(document).click(function(e) {
          if(e.target.id != "")
             e.stopPropagation(); 
          else   
             $('#button').text($("#mybutton").val());     
        });
    });
    </script>
    

    工作示例:https://jsfiddle.net/DinoMyte/s0duxn5f/3/

    【讨论】:

      【解决方案2】:

      &lt;button&gt; 转换为&lt;span&gt;

      <span class='button'>
        <input type='text' id='mybutton' />
      </span >
      

      然后给出&lt;span&gt; CSS,使其看起来和行为都像一个按钮:

      .button {
          cursor: pointer;
          // other css to make it look nice
      }
      

      然后添加一个click 处理程序

      $(".button").click(function(e) {
          // handle button
      });
      $("#mybutton").click(function(e) {
          // handle input
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多