【问题标题】:Text field select all / place cursor with jQuery文本字段全选/使用 jQuery 放置光标
【发布时间】:2012-03-06 10:33:38
【问题描述】:

我在编辑表单中有一个预先填充了值的文本字段。我想给它以下行为:

  • 在文本字段内单击会自动选择全部内容
  • 在区域内再次单击会取消选择所有内容并将光标置于用户单击的位置

这是我的代码:

// HTML
<input type="text" class="clickToSelect" value="myText" />

// jQuery
$(".clickToSelect").click(function(){
    $(this).select();
})

现在,当用户单击该字段时,所有文本都被选中,但当他们第二次单击时,所有文本仍被选中。任何想法如何在第二次单击时取消选择文本并放置光标?

【问题讨论】:

    标签: jquery input selection


    【解决方案1】:

    这样的?

        $(".clickToSelect").click(function(){
            if(!$(this).hasClass("click-selectall")){
               $(this).addClass("click-selectall");
               $(this).select();
            }
        });
    
       $(".clickToSelect").blur(function(){
            $(this).removeClass("click-selectall");
        })
    

    【讨论】:

    • 不客气,你是在用这个搜索字段吗?
    【解决方案2】:
    $(".clickToSelect").one('click', function(){
        $(this).select();
    })
    

    Working fiddle here.

    更新:Multiple-Clicky-Worky:

    $(".clickToSelect").click(function(){
        $this = $(this); // cache $(this) for better performance
        if (!$this.data('selected'))
        {
            $this.data('selected', true);
            $this.select();
        }
    }).blur(function(){
        $this.data('selected', false);
    });
    

    Fiddle

    【讨论】:

    • one() 很好,但第二次无法使用(如果用户单击-单击-单击-离开=然后单击)。这最后一个不起作用。
    • 感谢您 - Mvision 提供的解决方案似乎有效,但我认为您的解决方案也很好。可惜我不能接受两个答案:(
    • 不要吹毛求疵,而是将 data() 属性用于本质上不是真正数据的东西感觉不对,这就是我在回答中选择 addClass 的原因
    • @Mvision 我知道你从哪里来——尽管人们也可以争辩说状态是数据而不是类;)
    【解决方案3】:
    $.fn.slctText = function(start, end){
    
            var field = $J(this);
            if( field.createTextRange ){ 
                var selRange = field.createTextRange();
                selRange.collapse(true);
                selRange.moveStart("character", start);
                selRange.moveEnd("character", end);
                selRange.select();
            } else if( field.setSelectionRange ){ 
                field.setSelectionRange(start, end);
            } else {
                if( field.selectionStart ){ 
                    field.selectionStart = start;
                    field.selectionEnd = end;
                }
            }
            return $(this);
    }
    
    $.fn.setCurPos = function(pos){
    
            $(this).slctText(pos,pos);
            $(this).focus();
    }
    

    两者都是插件。使用它。

    【讨论】:

      猜你喜欢
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-16
      • 2011-05-10
      • 2010-12-20
      • 2013-05-08
      • 1970-01-01
      相关资源
      最近更新 更多