简体   繁体   中英

jQuery select on div content

I am making a small text editor, and for that, I would like a similar effect when a user selects some text as here: http://raphaelcruzeiro.github.io/jquery-notebook/

I was thinking of using the jQuery select event, but I can't seem to get it working on divs, only on input fields.

<!--<input type="text" class="writing-area" value="foo bar">-->
<div class="writing-area">foo bar</div>

<script>
$(".writing-area").select(function(){
    alert("Text marked!");
  });
</script>

You can see a demo here: http://jsfiddle.net/WL2nz/ The outcommented HTML works just fine, but the div version does not.

What am I doing wrong? Can select not be used on divs?

有关select事件的MDN参考说明,HTML5规范仅定义了输入和文本区域的select事件。

根据jQuery docs ,“此事件仅限于字段和框”。

From the jQuery page ( http://api.jquery.com/select/ ) for the .select() function:

"The select event is sent to an element when the user makes a text selection inside it. This event is limited to fields and boxes."

To get the effect you are look for, have you considered onmouseover or onclick with a clickable element?

In addition, the Dojo Toolkit is one place where you can get a nice tooltip to craft something similar to what you are looking for: click here

All answers are correct, but the plugin you have linked to, does it this way:

After using the keyboard or the mouse ( keyup , focus , mouseup ...) the plugin checks if something is select. If something is selected the bubble pops up.

The code is here

we highlighted the color of div text when hovers it and remove the color while non-hover the text.

$(".writing-area").hover(function(){
$(".writing-area").css('color','red');
 },function(){
$(".writing-area").css('color','');
});

http://jsfiddle.net/WL2nz/4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM