1. 程式人生 > >JS 實現textarea一行18個字元最多輸入5行的需求

JS 實現textarea一行18個字元最多輸入5行的需求

看到這個需求有一部分人認為給textarea加上rows和cols就可以滿足需求,emmmm...可以看看屬性的定義

所以還是要用JS來計算的,就是在value改變的時候呼叫計算函式,直接附上完整程式碼:

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Document</title>
</head>

<body>
	<textarea name="" id="textarea" cols="50" rows="5" ></textarea>
	<div id="countWarp"></div>
</body>
<script>
	var textarea = document.getElementById("textarea");
	var countWarp = document.getElementById("countWarp");
	// textarea.addEventListener('keyup', getCount, false);
	textarea.addEventListener('input', getCount, false);
	
	function splitStr18(str) {
		if (str.length <= 18) {
			return [str];
		}
		const getStr = str.slice(0, 18);
		const overStr = str.slice(19);
		return [getStr].concat(splitStr18(overStr));
	}

	function getCount(e) {
		const texts = e.target.value.split('\n');
		let filterTexts = [];

		for (var i = 0; i < texts.length; i++) {
			if (texts[i].length > 18) {
				const textArr = splitStr18(texts[i]);
				filterTexts = filterTexts.concat(textArr);
			} else {
				filterTexts.push(texts[i]);
			}
		}

		if (filterTexts.length > 5) {
			filterTexts = filterTexts.slice(0, 5)
			console.log("最後了~");
		}

		console.log(filterTexts);

		textarea.value = filterTexts.join('\n');
		countWarp.innerHTML = `祝福語(${filterTexts.length}/5 行)`;
	}
</script>

</html>

我當時專案中是在VUE中使用的,程式碼大同小異,再附上程式碼:
 

function splitStr18(str) {
    if (str.length <= 18) {
        return [str];
    }
    const getStr = str.slice(0, 18);
    const overStr = str.slice(19);
    return [getStr].concat(splitStr18(overStr));
}
/**  methods裡面
* 獲取輸入框資料
*/
getCount: function(e){
    this.isEnd = false;
    if(this.text.length==0){
        this.rowNum = 0;
        return;
    }
    let texts = this.text.split('\n');
    let filterTexts = [];

    for (var i = 0; i < texts.length; i++) {
        if (texts[i].length > 18) {
            let textArr = splitStr18(texts[i]);
            filterTexts = filterTexts.concat(textArr);
        } else {
            filterTexts.push(texts[i]);
        }
    }

    if (filterTexts.length > 5) {
        console.log("最後了~");
        filterTexts = filterTexts.slice(0, 5);
        this.isEnd = true;
        
    }
    console.log("獲取輸入框資料: ", filterTexts);
    this.$nextTick(()=>{
        this.text = filterTexts.join('\n');
    })

    console.log("=====", this.text);
    this.rowNum = filterTexts.length;
},