使用jQuery在焦点上select文本不工作在Safari和Chrome

我有以下jQuery代码(类似于这个问题 ),在Firefox和IE中工作,但在Chrome和Safari失败(没有错误,只是不工作)。 任何想法的解决方法?

$("#souper_fancy").focus(function() { $(this).select() }); 

这是onmouseup事件导致select被取消select,所以你只需要添加:

 $("#souper_fancy").mouseup(function(e){ e.preventDefault(); }); 
 $('#randomfield').focus(function(event) { setTimeout(function() {$('#randomfield').select();}, 0); }); 

这对inputtypes=“文本”元素工作正常。 什么样的元素是#souper_fancy?

 $("#souper_fancy").focus(function() { $(this).select(); }); 

只要防止鼠标hover的默认情况下,文本select始终打开。 MOUSEUP事件负责清除文本select。 但是,通过防止其默认行为,您无法使用鼠标取消select文本。

为了避免这种情况,让文本select再次运行,您可以在FOCUS上设置一个标志,从MOUSEUP中读取并重置,以便将来的MOUSEUP事件按预期工作。

 $("#souper_fancy").focus(function() { $(this).select(); //set flag for preventing MOUSEUP event.... $this.data("preventMouseUp", true); }); $("#souper_fancy").mouseup(function(e) { var preventEvent = $this.data("preventMouseUp"); //only prevent default if the flag is TRUE if (preventEvent) { e.preventDefault(); } //reset flag so MOUSEUP event deselect the text $this.data("preventMouseUp", false); }); 

虽然这可以在IE,Firefox,Chrome,Safari和Opera中select,但它不会让您通过在Firefox,Chrome和Safari中再次单击进行编辑。 不完全确定,但我认为这可能是由于这3个浏览器重新发出一个焦点事件,即使该字段已经有焦点,因此从来不允许你实际插入光标(因为你再次select它),而在IE和歌剧它似乎没有这样做,焦点事件不会再次被解雇,因此光标被插入。

我在这篇文章中发现了一个更好的解决scheme,它没有这个问题,可以在所有浏览器中使用。

这应该也适用于铬:

 $("#souper_fancy").focus(function() { var tempSouper = $(this); setTimeout(function(){ tempSouper.select(); },100); }); 

因为使用setTimeout时闪烁,所以还有另一个基于事件的解决scheme。 这样,“焦点”事件附加“mouseup”事件,事件处理程序再次分离。

  function selectAllOnFocus(e) { if (e.type == "mouseup") { // Prevent default and detach the handler console.debug("Mouse is up. Preventing default."); e.preventDefault(); $(e.target).off('mouseup', selectAllOnFocus); return; } $(e.target).select(); console.debug("Selecting all text"); $(e.target).on('mouseup', selectAllOnFocus); } 

然后连线第一个事件

  $('.varquantity').on('focus', selectAllOnFocus); 

试试这个:

 $("#souper_fancy").focus(function() { setTimeout(function(){ $(this).select(); },100); });