创建 URL 锚点到文本选择

create URL with anchor to text selection

我想创建一个 URL 指向我编写的 Web 服务,http://mycoolthing.com,以及一个指向 文本选择的 #-anchor 在那个页面上。

是否可以在 HTML/JS 中创建引用 Selection 或 RangeObject 的锚点?

看看 https://developer.mozilla.org/en-US/docs/Web/API/document.execCommand

createLink

Creates an anchor link from the selection, only if there is a selection. This requires the HREF URI string to be passed in as a value argument. The URI must contain at least a single character, which may be a white space. (Internet Explorer will create a link with a null URI value.)

喜欢

document.execCommand('createLink', false, 'http://google.com');

根据此站点,您可以使用 javascript 在页面中查找一些文本。

http://www.javascripter.net/faq/searchin.htm

也许您可以为网站创建一个 link 并使用 GET 或 POST 包含文本选择,这样当其他页面加载时,您可以使用 [=23 转到文本选择=] 和上一页的信息。

首页是这样的:

window.location.href="url?text=textToFind"

在另一页:

$(function () {
window.find(window.location.search)
});

您可以使用

获取选定(突出显示)的文本
var txt = window.getSelection().toString();

然后使用该值构建锚点

href="abc.html#' + txt;

正如我在评论中提到的,这里是 select 文本的选项,方法是使用 JavaScript 和 url 上的散列 (#)。

分为两部分:

  1. 调用页面将有一个 link 到目标页面(它们可以相同),并带有一个 # 指示您想要 select 的文本(或者如果你知道的,元素的 ID):

    <a href="myPage.html#Lorem">Link to my page with Lorem select</a>

  2. 目标页面将包含一些 JavaScript 代码,这些代码将 select # 中指示的文本(如果散列是有效的元素 ID,它将 select 该元素中的文本而不是文本)。

*请注意,对于此解决方案,我使用了 Selecting text in an element (akin to highlighting with your mouse)(Kimtho6 的解决方案)

中的一些代码
/**
 * SelectText: function from  (Kimtho6 solution)
 * 
 * element: string that contains an element id (without the #)
 */
function SelectText(element) {
    var doc = document;
    var text = doc.getElementById(element);    
    if (doc.body.createTextRange) { // ms
        var range = doc.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        var selection = window.getSelection();
        var range = doc.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);

    }
}

/**
 * selectHashText: function that selects the first appearance of a text (or an element with the id) indicated in the location hash
 */
function selectHashText() {

    // check if there's an element with that ID
    if ($(document.location.hash).length == 0) {

        // select some text in the page
        var textToSelect = document.location.hash.substring(1);

        // if it's not an empty hash
        if (textToSelect != "") {

            // iterate the different elements in the body
            $("body *").each(function() {

                // if one contains the desired text
                if ($(this).text().indexOf(textToSelect) >= 0) {

                    // wrap the text in a span with a specific ID
                    $(this).html(
                        $(this).html().replace(textToSelect, "<span id='mySelect'>" + textToSelect + "</span>")
                    );

                    // select the text in the specific ID and stop iteration
                    SelectText("mySelect");
                }
            });
        }

    } else {
        // select the content of the id in the page
        SelectText(document.location.hash.substring(1));
    }
}

// execute the text selection on page load and every time the hash changes
$(window).on("hashchange", selectHashText);
$(document).ready(function() { selectHashText(); });

我创建了这个 jsfiddle, but it doesn't take the # so it doesn't help much. You can also see it on this web page。请注意,它与 jsfiddle(及以上)中的代码相同,只是在一页上。


更新:(根据以下评论详述)

在不使用散列的情况下,您可以将想要的文本作为 GET 或 POST 中的参数 select 传递(为简单起见,我将使用 GET):

<a href="myPage?select=Lorem">Select Lorem</a>

然后使用您的后端语言(我使用 PHP,您可以使用任何其他甚至 JavaScript 解析位置 href),将文本保存到 textToSelect 变量中我以前用过的。作为最后一步,将 .text() 替换为我使用的 .html()(因此标签也包含在搜索中)

/**
 * gup: function from  (Haim Evgi's solution)
 * 
 * name: string that contains the name of the parameter to return
 */
function gup( name ) {
    name = name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
    var regexS = "[\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    return results == null ? null : results[1];
}

/**
 * selectHashText: function that selects the first appearance of a text (or an element with the id) indicated in the "select" parameter
 */
function selectTextAcross() {

    // get the "select" parameter from the URL
    var textToSelect = decodeURIComponent(gup("select"));

    // if it's not an empty hash
    if (textToSelect != "") {

        // iterate the different elements in the body
        $("body *").each(function() {

            // if one contains the desired text
            if ($(this).html().indexOf(textToSelect) >= 0) {

                // wrap the text in a span with a specific ID
                $(this).html(
                    $(this).html().replace(textToSelect, "<span id='mySelect'>" + textToSelect + "</span>")
                );

                // select the text in the specific ID and stop iteration
                SelectText("mySelect");
            }
        });
    } 
}

$(document).ready(function() { selectTextAcross(); });

你可以see it working on this web page.

关于此解决方案:

  • 有效(嘿!聊胜于无!:P)
  • 您可以包含 html 标签(不能使用 # one)
  • 您需要知道文档的来源
  • 生成的代码可能无效,结果可能不是预期的(我测试过的所有浏览器,它们在第一个 "crossed" 标记后停止 selecting)

基于 chromium 的浏览器现在支持滚动到文本片段

https://chromestatus.com/feature/4733392803332096#:~:text=This%20feature%20allows%20a%20user,and%20scrolls%20it%20into%20view.