javascript
  • jquery
  • html
  • css
  • html5
  • 2016-03-13 61 views 0 likes 
    0

    我想在運行時將某些單詞更改爲輸入框中的用戶類型。反正有這樣做,因爲當我使用替換jQuery函數它會替換值,但不允許我改變它的CSS。由於將輸入框文本的顏色更改爲用戶類型

    這是我迄今取得

    這是使用Javascript:

    $("#submit-button").click(function(){ 
        var oldString = 'john', 
        newString = '<span id="newChrome">chrome</span>' 
        $("#text-editor").val($("#text-editor").val().replace(RegExp(oldString,"gi"),newString)); 
    }); 
    

    這是HTML

    <input id="text-editor" maxlength="200" width:200px; /> 
    <button id="submit-button">Submit</button> 
    
    +0

    你能解釋一下嗎?你想在用戶輸入時改變某個單詞的顏色?我看到你想替換''而不是'john'字符串?!你不能這樣做。 – Pedram

    +0

    你不能把html內容放在輸入裏面,並且設計它的樣式 – LGSon

    +0

    使用textarea來代替 –

    回答

    0

    使用contenteditable div元素就可以實現你所想在大多數現代瀏覽器中實現。

    $("#submit-button").click(function() { 
     
        var oldString = 'john', 
     
        newString = '<span class="newChrome">chrome</span>', 
     
        regex = new RegExp(oldString, "gi"), 
     
        value = $("#text-editor").html(), 
     
        str = value.replace(regex, newString); 
     
        $("#text-editor").html(str); 
     
    }); 
     
    $("#text-editor").on('input',function(){ 
     
        $a = $(this).find('span') 
     
        $a.filter(function(){ 
     
        return $(this).html() != 'john'; 
     
        }).removeClass('newChrome'); 
     
        $a.filter(function(){ 
     
        return $(this).html() == 'chrome'; 
     
        }).addClass('newChrome'); 
     
    });
    .newChrome{ 
     
        color: red; 
     
    } 
     
    #text-editor{ 
     
        outline: 1px solid black; 
     
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
     
    <div contenteditable="true" id="text-editor" maxlength="200" style="width:200px;"></div> 
     
    <button id="submit-button">Submit</button>

    +0

    謝謝。不完全是我想要的,但有幫助。 –

    +0

    @SydAbdRehmanKazmi是的。不是最好的主意。其他解決方案是使用一個輸入和div與show hide交替基於焦點和clikc。 – RRK

    +0

    你能幫我解決另一件事嗎?即使在我鍵入Chrome之後,它也會爲下一個字詞保留相同的CSS。如何刪除它? –

    相關問題