質問

I was trying to change the behaviour of an HTML page with Javascript so whenever I click a blank space in a text (not textArea) between two words, instead of selecting that blank space, it selects the words before and after the blank space. I was trying to do it this way, but I am not able to do it:

function getBothWords() {
  if (window.getSelection()) {
    var sel = window.getSelection();
    var blank = " ";
    if(sel == blank) {
      ...
    }
  }
}

I also was trying to play with:

window.getSelection().getRangeAt(0)

But still nothing. Any ideas? Thanks :)

役に立ちましたか?

解決 3

There is an amazing method in class Selection called modify() which is created for that purpose. In my case, the solution would be:

function select() {
  if (window.getSelection) {
    var s = window.getSelection();
    var blank = " ";
    if(s == blank) {
      selectBothWords(s);
    }
  }
}

function selectBothWords(s) {
    s.modify("move", "backward", "word");
    s.modify("extend", "forward", "word");
    s.modify("extend", "forward", "word");
}

The function select() checks that the selection is a 'blank space' (loosely). Then, the function selectBothWords() uses modify to move the selection one word backwards, then, extend it two words forward.

他のヒント

When you only click on a blank space, the selection will be collapsed. You can try something like this:

function getBothWords() {
    var sel,
        range = document.getSelection().getRangeAt(0);
    if (range.collapsed) {
        range.setEnd(range.startContainer, range.startOffset + 1);
    }
    sel = range.toString();
    if (sel ===  ' ') {
        ...
    }
}

A live demo at jsFiddle.

You should introspect the selection object and see that there is an anchorNode element available and an anchorIndex.

See the MDN Docs on selection.

The short is you need to look at your anchorNode and anchorOffset.

sel.anchorNode.nodeValue[sel.anchorNode.anchorOffset] might be the first character of your selection. Log the sel object to the console and start poking around. Some simple math should solve the issue from there. Of course it might not be a text node.

Be sure to read the definitions on the page since there are some gotchas that can be confusing.

More to the point, something like this is a dirty hack job:

var subLen = s.focusNode.nodeValue.substr(s.focusOffset).trim().indexOf(' ')+2;
var selectedWordWitSurroundingSpaces = s.focusNode.nodeValue.substr(s.focusOffset, subLen);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top