前端學習-對一段文字進行查找、截取、切割

效果

  1. 查找(找到原文中對應的輸入內容並改變其顏色)
    在這裏插入圖片描述
    在這裏插入圖片描述
  2. 截取(找到輸入的文字顯示在下方並刪除原文中的內容)
    在這裏插入圖片描述
    在這裏插入圖片描述
  3. 切割(根據輸入內容切割原文,逐句顯示)
    在這裏插入圖片描述
    在這裏插入圖片描述

html標籤

		<p id="paragraph">站在戶外,輕輕的噓一口氣,一團白霧裹着一份溫暖嫋嫋升空,在半空中伸展,氤氳,半晌又匯入了乾冷的空氣。剛剛燃起的一點希望有破滅了,消失得輕悄而又平靜,彷彿從來就不曾有過,又恍惚有過這末一份特別的溼潤。小苗長成大樹,到了冬天便成了老樹,老樹枝椏交錯,只有幾片稀稀落落的葉子點綴着生命的痕跡。樹皮微現焦黃,彷彿在火上烤了許久,煎熬的失了神采,半捲曲着好像隨時都會墜地。</p>
		<div class="form" id="form">
			<div class="form-group">
				<input class="form-input" id="search" type="text" placeholder="請輸入需要查找的字符">
				<button class="btn" onclick="search()">查找</button>
			</div>
			<div class="form-group">
				<input class="form-input" id="select" type="text" placeholder="請輸入需要截取的內容">
				<button class="btn" onclick="select()">截取</button>
			</div>
			<div class="form-group">
				<input class="form-input" id="cut" type="text" placeholder="請輸入切割關鍵字符">
				<button class="btn" onclick="cut()">切割</button>
			</div>
		</div>
		<p id="show" style="color: #5E5E5E;"> </p>

js代碼

		<script>
			//查找
			function search() {
				var text = document.getElementById("paragraph").innerHTML;
				var sh = document.getElementById("search").value;
				var start = text.indexOf(sh); //獲得字符串的開始位置
				var shresult = text.substring(start, start + sh.length); //截取字符串
				text = text.replace(shresult, '<span style="color:#E83E8C">' + shresult + '</span>');//替換文本內容
				document.getElementById("paragraph").innerHTML = text;
			}
			//截取
			function select() {
				var text = document.getElementById("paragraph").innerHTML;
				var st = document.getElementById("select").value;
				var start = text.indexOf(st); //獲得字符串的開始位置
				var stresult = text.substring(start, start + st.length); //截取字符串
				text = text.replace(stresult, "");
				document.getElementById("paragraph").innerHTML = text;
				document.getElementById("show").innerHTML = stresult;
			}
			// 切割
			function cut() {
				var text = document.getElementById("paragraph").innerHTML;
				var ct = document.getElementById("cut").value;
				var ctre = text.split(ct);
				for (i = 0; i < ctre.length; i++) {
					document.getElementById("show").innerHTML += ctre[i] + '</br>';
				}
			}
		</script>

css

#paragraph,#show {
	font-size: 18px;
	font-family: MFYanSong_Noncommercial;
	font-weight: 400;
	line-height: 30px;
	padding: 10px;
}


.form {
	position: fixed;
	left: 20px;
	top: 140px;
	color: white;
	width: 500px;
	line-height: 40px;
}


.form-input {
	width: 250px;
	color: #000000;
	font-weight: 100;
	border: none;
	background: none;
	outline: none;
	padding: 5px;
	font-size: 13px;
}


.btn {

	width: 60px;
	height: 28px;
	background: rgba(0, 143, 213, 1);
	border: 1px solid rgba(0, 142, 216, 1);
	border-radius: 3px;
	color: #FFFFFF;
	font-size: 6px;
	font-family: Microsoft YaHei;
	cursor: pointer;
}


input:-webkit-autofill {
	box-shadow: 0 0 0px 1000px white inset !important;
}

#show{
	position: absolute;
	top:250px
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章