简体   繁体   中英

How can I prepend 4 white spaces to an element and then remove them with javascript?

When the user presses the tab key inside a content-editable div I prepend 4 whitespaces to the text inside that p tag like so:

  containerWithCaret = rangy.getSelection().anchorNode.parentNode
  $(containerWithCaret).prepend '    '

Since the div is set to white-space pre the tab shows up fine. But now when the user presses shift + tab I am not sure how to untab the white spaces? How can simulate the delete key being pressed 4 times? I tried using jquery to set the text of the div to a substring minus the first 4 character but got messy results with the caret.

Is there a good way to untab by keeping track of how many tabs each line has and to remove them how can I simulate the delete key being pressed 4 times?

Try this:

$( ".inner" ).prepend( "    " );

and for removing these spaces you can use:

myString.replace(/ +/g, '');

I think this will work.

happyCoding :D

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