如何根据限制更改前几个字符的颜色,并将其保留在div

时间:2015-07-02 12:13:54

标签: javascript jquery html

我想做的是我有两个div。一个用于写内容,另一个用于显示限制。当我在第一个div中写入任何单词时,第二个div计数减少一个。现在当count为0时,我希望第一个div中的所有单词都有红色的背景颜色,当我写下一个没有任何背景的正常单词时

到目前为止我尝试了什么: -

 <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

<div contenteditable="true" class="jqte_editor" id= "content"></div><br />
        <div class="pin_words">
            <span id="word_count_line"><span id="more_words">10</span> more category for <span id="points">adding</span>category</span>
            <input type="hidden" id="pin_word_limit" value="10">
            <input type="hidden" id="pin_points" value="20">
        </div>


<style>
.jqte_editor {
    border: 2px solid green;
    float: left;
    height: 100px;
    width: 100%;
}
</style>
<script type = "text/javascript">
function wordTracker(selector, pin_words){
        $this1 = $(selector);
        var value = $this1.text();
        //console.log("==>"+(value.length)+"<==");
        var wordLimit = parseInt($(pin_words+" > #pin_word_limit").val());
        var points = $(pin_words+" > #pin_points").val();
        if(value=="") $(pin_words+" > #word_count_line > #more_words").text(wordLimit);
        var wordCount = value.trim().split(' ').length;
        var tbwWords = wordLimit - wordCount;
        if(tbwWords > 0) 
            $(pin_words+" > #word_count_line").html('<span id="more_words">'+tbwWords+'</span> more words for '+points+' points</span>').css('font-weight', 'normal');
        else 
            $(pin_words+" > #word_count_line").text(points+' Points').css('font-weight', 'bold'); 

        if(value.length == 0) $(pin_words+" > #word_count_line").html('<span id="more_words">'+wordLimit+'</span> more words for '+points+' points</span>').css('font-weight', 'normal');

        if(tbwWords == 0){
            var search1 = $('.jqte_editor').text();
            //var regex = new RegExp(search1,'gi');
            $(".jqte_editor").html($(".jqte_editor").text().replace(search1, "<span style ='background-color:red'>"+search1+"</span>"));
            setEndOfContenteditable(document.getElementById('content'));
       }
    }

    $(document).ready(function(){
        $('.jqte_editor').keyup(function(){
            wordTracker(this, '.pin_words');
        });
    });

    function setEndOfContenteditable(contentEditableElement)
    {
        var range,selection;

        if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
        {
            range = document.createRange();//Create a range (a range is a like the selection but invisible)
            range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
            range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
            selection = window.getSelection();//get the selection object (allows you to change selection)
            selection.removeAllRanges();//remove any selections already made
            selection.addRange(range);//make the range you have just created the visible selection
            console.log(range);
            console.log(selection);
        }
        else if(document.selection)//IE 8 and lower
        { 
            range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
            range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
            range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
            range.select();//Select the range (make it the visible selection
        }
    }
</script>

注意:当限制结束时,代码的工作量大约为95%。但之后我需要按空格+任何一个角色,然后只有下一个没有颜色。

如果您复制整个代码并运行,您可以轻松理解我的问题。

3 个答案:

答案 0 :(得分:1)

如果我理解你的问题,你想要用红色,只有前10个字。

我使用这个小jQuery/js段来计算前10个单词:

var firstTenWords = string.split(' ').slice(0,9).join(' ');

然后在string1中添加新变量firstTenWords,而不是<span>

我在您发布的脚本的第19行行之后进行了此更改:

var firstTenWords = search1.split(' ').slice(0,9).join(' ');
$(".jqte_editor").html($(".jqte_editor").text().replace(firstTenWords, "<span style ='background-color:red'>"+firstTenWords+"</span>"));

//Continues with your code: setEndOfContenteditable(document.getElementById('content'));
//And so on...

以下是您的代码和我的更改所做的工作小提琴:https://jsfiddle.net/jfdwrdfx/2/

答案 1 :(得分:1)

我为您的查询创建了一个小提琴。我希望这能解决您的问题。

&#13;
&#13;
$('textarea').on('input', function() {
  var word = 0,
    lastLetter;

  $('#output > span').text('');
  this.value.split('').forEach(function(letter, i) {
    if (letter === ' ' && lastLetter !== ' ') word++;
    lastLetter = letter;
    if (word < 5) {
      $('#output span:first').append(letter);
    } else {
      $('#output span:last').append(letter);
    }
  });
});

$('textarea').focus();
&#13;
textarea,
#output {
  width: 500px;
  height: 10em;
  padding: 0.2em;
  margin: 0.2em;
  box-sizing: border-box;
  font: 13px arial;
  border: 1px solid silver;
  white-space: pre-wrap;
}
textarea {
  -webkit-text-fill-color: transparent;
  overflow: auto;
}
#output {
  position: absolute;
  pointer-events: none;
  z-index: 1;
}
#output span:first-of-type {
  color: green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"><span></span><span></span></div>
<textarea></textarea>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

只要有单一的空间,我的方法就可以工作......恕我直言不好......

但是这里......

https://jsfiddle.net/cbc1b9ka/

var limit = 5;
var remaining = $('.remaining').text(limit);
var overlay = $('.overlay');
var input = $('input');

overlay.height(input.height());


input.on('input',function(){
    var text = $(this).val();
    overlay.text(text);
    var words = text.match(/\b[^\s]+\b/gi);
    if (words.length>limit) {
        var first = words.splice(0,limit);
        var ele1 = $('<span class="redbg">').text(first.join(' '));
        var ele2 = $('<span>').text(" "+words.join(' '));
        overlay.html('');
        overlay.append(ele1).append(ele2);
    }

});