0

I'm working on a JavaScript wrapper around the Rangy JavaScript plugin. What I'm trying to do: given a jQuery selector and a range, detect if the range is contained within the selector. This is for a space where a user will read a document and be able to make comments about particular sections. So I have a div with id="viewer" that contains the document, and I have an area of buttons that do things after a user selects some text. Here is the (broken) function:

function selectedRangeInRegion(selector) {
    var selectionArea = $(selector);
    var range = rangy.getSelection().getRangeAt(0);
    var inArea = (selectionArea.has(range.startContainer).length > 0);

    if (inArea) {
        return range;
    } else {
        return null;
    }
}

It appears that selectionArea.has(range.startContainer) returns an array of size 0. I have tried wrapping like: $(range.startContainer). Any tips?


I developed a solution for this problem. This assumes you have a div selector and that your content does not have any divs:

function containsLegalRange(selector, range) {
  var foundContainingNode = false;

  var container = range.commonAncestorContainer

  var nearestDiv = $(container).closest("div");    
  if (nearestDiv.attr("id") == selector) {
    return true
  }
  else {
    return false
  }
}
4

2 に答える 2

2

has()渡すパラメータはセレクター文字列または DOM 要素のいずれかですrange.startContainerが、実際にはテキスト ノードまたは要素である可能性のある DOM ノードです。

あなたが望んでいるほど簡単な方法はないと思います。以下は、私が頭のてっぺんから考えることができるのと同じくらい簡単です。

jsFiddle: http://jsfiddle.net/TRVCm/

コード:

function containsRange(selector, range, allowPartiallySelected) {
    var foundContainingNode = false;
    $(selector).each(function() {
        if (range.containsNode(this, allowPartiallySelected)) {
            foundContainingNode = true;
            return false;
        }
    });
    return foundContainingNode;
}
于 2011-06-25T23:03:22.720 に答える
0

.has() は時々奇妙になり.length == 0、想定されていないときに生成される可能性があります。代わりにこの方法を試してください:

function selectedRangeInRegion(selector) {
  var range = rangy.getSelection().getRangeAt(0);
  var selectionArea = selector + ':has(\'' + range.startContainer + '\')';
  var inArea = $(selectionArea).length > 0);
  if (inArea) {
    return range; 
  }
  else {
    return null;
  }
}
于 2011-06-24T22:53:24.733 に答える