开发者

how to Select All words when a div focus using jquery

this is my code :

<di开发者_如何学Pythonv id="box" style="border:1px solid red;height:100px;width:150px;position:relative;background:#eee">
        <div id="head" style="background:black">drag me</div>
        <div id="content" contenteditable=true style="border-bottom:1px solid red;height:70px;margin-bottom:5px;"> edit it </div>
        <input id="ok" type="button" value="ok"/>
        <input id="cancel" type="button" value="cancel"/>
    </div>

and the script is :

$('#content').focus()

the demo is here :http://jsfiddle.net/VRxZe/8/

how can i select 'edit it'

thanks


If you want to select text inside some element, you can use Ranges. The code below should work with Firefox and Opera and Chrome. Another story is IE. For this browser you will have to create new TextRange object and use its methods moveToElementText and select.

var content = document.getElementById('content');
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(content);
selection.removeAllRanges();
selection.addRange(range);
content.focus()

The code below is for IE

var content = document.getElementById('content');
var rng = document.body.createTextRange();
rng.moveToElementText(content);
rng.select();
content.focus()

Hope this helps.


Well, you are almost there :)

  $('#box').focus(function()
           {
                $('#content', this).select();

           });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜