當用戶 輸入 my 時input,我希望 是綠色的
例如: 10000 --> " " 應該是綠色,10000 應該是黑色
當用戶-輸入 my 時input,我希望-是紅色的
例如:-10000 --> "-" 應該是紅色,10000 應該是黑色
我的想法是使用::first-letter,但我意識到它不起作用input
這完全可以用 css 和 javascript 實作嗎?我需要一些花哨的正則運算式來完成這個嗎?
input {
font-size: 100px;
}
/* only - should be red */
input::first-letter {
color: red;
}
/* only should be green */
input::first-letter {
color: green;
}
<!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" />
<link rel="stylesheet" href="styles.css" />
<title>Static Template</title>
</head>
<body>
<input type="text" />
</body>
</html>
uj5u.com熱心網友回復:
首先使用 獲取<input>元素.getElementsByTagName('input')[0],然后您可以在 上附加事件偵聽器keyup。從這里,您可以使用.style.color基于以下內容更新顏色.value[0]:
顯示代碼片段
const target = document.getElementsByTagName('input')[0];
target.addEventListener('keyup', function() {
if (this.value[0] === '-') {
this.style.color = 'red';
}
else if (this.value[0] === ' ') {
this.style.color = 'green';
}
else {
this.style.color = 'black';
}
})
input {
font-size: 100px;
}
<!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" />
<link rel="stylesheet" href="styles.css" />
<title>Static Template</title>
</head>
<body>
<input type="text" />
</body>
</html>
請注意,上面的代碼段僅檢查輸入的第一個字符。如果您想檢查任何目標字符,你可以在回圈的發生.value。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/370130.html
標籤:javascript html css
上一篇:我需要一個handleDelete過濾器函式來回應onclick按鈕。我可以為一個物件陣列撰寫代碼,但這是一個物件物件
