简体   繁体   English

用Javascript突出显示文字

[英]Highlight slices of text with Javascript

Problem 问题

Suppose that in the backend of my Web application I have a generic string of letters: 假设在我的Web应用程序的后端 ,我有一个通用的字母字符串:

seq = AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

and an array of positions in such a string: 以及这样的字符串中的位置数组:

pos = [(0, 2), (4, 8)]

I need to render this sequence in the frontend by splitting it every n characters. 我需要通过在前端每n字符拆分一个序列来呈现此序列。 Then when a user clicks a button I need to highlight the sequence between two parameters (taken from pos ) for which the button refers to. 然后,当用户单击按钮时,我需要突出显示按钮所引用的两个参数(取自pos )之间的顺序。

My solution 我的解决方案

I solve this by implementing a Javascript function formatSequence which splits seq every n characters and iterates through the pos array in order to wrap each substring inside a span tag. 我通过实现Javascript函数formatSequence来解决此问题,该函数每隔n字符分割seq并遍历pos数组,以便将每个子字符串包装在span标记内。 The result is something like this: 结果是这样的:

<pre>
    <span class="A">AA</span>AA<span class="B">A</span>
    <span class="B">AAA</span>AA
    AAAAA
</pre> 

When the user clicks the button referring to the class A I simply change the CSS background rule for class A . 当用户点击该按钮指的是类的A ,我只是改变了类CSS背景规则A

It works :) But the function formatSequence is way too complicated imho. 它有效:)但是函数formatSequence太复杂了,恕我直言。 It was a pain dealing with multiple lines. 处理多行是很痛苦的。 I prefer not posting the code since I am looking for other approaches not changing the code of such function. 我宁愿不发布代码,因为我正在寻找其他不更改此类功能代码的方法。

A better solution? 更好的解决方案?

I think that a (better?) solution would be to implement a function that given two parameters start and end it dynamically highlights the text between them. 我认为,(更好?)解决方案是实现一个给定的两个参数的函数startend它动态地强调了这两者之间的文本。 But it appears to be even more complicated than the previous one (remember that the sequence must be split every n characters and thus the highlight must be multilines). 但是它似乎比前一个更加复杂(请记住,序列必须每n字符分割一次,因此突出显示必须是多行)。

Any suggestions? 有什么建议么? Better approach to solve this? 解决这个问题的更好方法?

One simple solution would be just to print the full seq multiple times into the HTML and hide every row you don't need at the time. 一种简单的解决方案是将完整的seq多次打印到HTML中,并隐藏当时不需要的每一行。 When a user clicks on a button, another row would be displayed (and the first one would be hidden). 当用户单击一个按钮时,将显示另一行(第一行将被隐藏)。

HTML: HTML:

<div class="rows"></div>
<div class="buttons"></div>

JavaScript (depending on jQuery): JavaScript(取决于jQuery):

(function generateRowsAndButtons() {
    var sequence = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
    var position = [ [0,2], [4,8] ];
    var $rows = $('.rows');
    var $buttons = $('.buttons');

    for(var i = 0; i < position.length; i++) {
        if(position[i].length !== 2 || position[i][0] > position[i][1]) {
            console.log("every position array needs exactly two values with the second larger than the first one");
            continue;
        }
        // the index is used for mapping the button the highlight position
        var row = '<div class="row" data-index="' + i + '" style="display: none;">';

        // you should add some checks here, if position larger then the length of the string to avoid some misbehaviors. this is of course only necessary if you aren't validating the values on another place.
        row += sequence.substring(0, position[i][0]);
        row += '<span class="highlighted">';
        row += sequence.substring(position[i][0], position[i][1]);
        row += '</span>';
        row += sequence.substring(position[i][1]);
        row += '</div>';

        var $row = $(row);
        $rows.append($row);

        // a button needs the index to find the link the highlighted value
        var $button = $('<button data-index="' + i + '">' + position[i] + '</button>');
        $buttons.append($button);
    }

    $buttons.find('button').click(function() {
        var index = $(this).data('index');

        // hide every row, except the one with the correct index
        $rows.find('.row').hide().filter('[data-index="' + index + '"]').show();
    });

})();

CSS: CSS:

.row .highlighted {
    background: yellow;
}

Here is a jsFiddle: https://jsfiddle.net/y8uoou1L/2 这是一个jsFiddle: https ://jsfiddle.net/y8uoou1L/2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM