最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check whether text is highlighted using window.getSelection() - Stack Overflow

programmeradmin1浏览0评论

I am writing a javascript function that needs to check first whether the user has highlighted / selected some text on the page. I read online that this should work:

if ( typeof window.getSelection() != "undefined" ) {
    var x = window.getSelection().toString();
}
else {
    //nothing is selected, so use default value
    var x = "default value";
}

But that did not work because even when nothing is selected, window.getSelection() returns an object.

if ( typeof window.getSelection().toString() !== "" ) {
    var x = window.getSelection().toString();
}
else {
    //nothing is selected, so use default value
    var x = "default value";
}

But even though window.getSelection().toString() returns an empty string, it still uses that empty string rather than the default value.

Finally, if ( window.getSelection() ) did not work either.

How can I know whether something is selected?

I am writing a javascript function that needs to check first whether the user has highlighted / selected some text on the page. I read online that this should work:

if ( typeof window.getSelection() != "undefined" ) {
    var x = window.getSelection().toString();
}
else {
    //nothing is selected, so use default value
    var x = "default value";
}

But that did not work because even when nothing is selected, window.getSelection() returns an object.

if ( typeof window.getSelection().toString() !== "" ) {
    var x = window.getSelection().toString();
}
else {
    //nothing is selected, so use default value
    var x = "default value";
}

But even though window.getSelection().toString() returns an empty string, it still uses that empty string rather than the default value.

Finally, if ( window.getSelection() ) did not work either.

How can I know whether something is selected?

Share Improve this question asked Jun 10, 2013 at 15:53 Bryan GentryBryan Gentry 8631 gold badge8 silver badges25 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

This will work: http://jsfiddle/tknkh9xa/1/

(window.getSelection().toString() != "")

Your problem was that you were checking the typeof on the result of the toString()... which would not be an empty string (it would be "string").

Also, since an empty string is a falsy value, you could do just
if(window.getSelection().toString())

发布评论

评论列表(0)

  1. 暂无评论