簡體   English   中英

如何使輸入中鍵入的文本顯示在單獨的div中

[英]How to make the text that are typed inside the input to appear into a seperate div

我有一個輸入字段和一個單獨的段落。 現在如何將輸入中鍵入的文本也顯示在paragrah中?

HTML代碼

<input type="text" />
<p>facebook/<span>your.username</span> </p>

的CSS

input{
    width: 300px;
    height: 30px;
}
span {
    font-weight: bold;
}

使用keyup事件:

$(function() {
    $('input').on('keyup', function() {
        var username = $(this).val();

        if(username.length > 0) {
           $('p > span').html(username);
        } else{
           $('p > span').html('your.username');
        }
    });
});

參見工作jsfiddle: http//jsfiddle.net/VDesign/yqt8tx3b/2/

嘗試這個:

$(document).ready(function() {
    // When DOM is ready to be manipulated

    $('input').on('keyup', function() {
        // On each key-up in textbox

        $('p span').text($.trim($(this).val()) || 'your.username');
        // Set the value of textbox inside the span
    });
});

演示: https : //jsfiddle.net/tusharj/4yfswj3p/

這樣,您可以實時更改p標簽。

 $('#txt').on('input',function(e){ $('p').html($(this).val()); }); 
 input{ width: 300px; height: 30px; } span { font-weight: bold; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="txt"/> <p>facebook/<span>your.username</span> </p> 

這是一個純JavaScript解決方案,使用input事件將在您鍵入時更新另一個元素的內容,還包括檢查input元素是否為空。

 var input=document.getElementById("input"),output=document.getElementById("output"); input.addEventListener("input",function(){ output.innerHTML="facebook.com/"+(this.value.trim()||"your.username"); },0); 
 <input id="input" type="text"> <p id="output">facebook.com/your.username</p> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM