Front End/🌈 JavaScript
text box 입력시 label text 위치 변경하기
James Wetzel
2024. 4. 12. 11:56
CSS
<style type="text/css">
.container {
position: relative;
width: 100px;
height: 23px;
}
.placeholder-label {
position: absolute;
top: 4px;
right: 40px;
pointer-events: none;
color: #888;
transition: right 0.3s, font-size 0.3s;
}
.focused {
top: 4px;
right: 20px;
font-size: 10px;
}
.blured {
top: 4px;
right: 40px;
font-size: 13px;
}
</style>
HTML
<div class="container">
<input type="number" id="krw" class="qwms-inp__box" style="width:100px;" placeholder="0" onfocus="Page.onFocus('placeholder_krw')" onblur="Page.onBlur('placeholder_krw', this)">
<label for="krw" id="placeholder_krw" class="placeholder-label">KRW</label>
</div>
Javascript
var Page = {
onBlur: function (placeholder_id, object) {
const placeholder = document.getElementById(placeholder_id);
if (object.value.trim() === '') {
placeholder.classList.remove('focused');
placeholder.classList.add('blured');
}
},
onFocus: function (placeholder_id) {
const placeholder = document.getElementById(placeholder_id);
placeholder.classList.add('focused');
placeholder.classList.remove('blured');
},
}
샘플2
<!DOCTYPE html>
<html>
<head>
<title>Label Position on Text Box Click</title>
<style type="text/css">
.container {
position: relative;
width: 220px;
height: 40px;
}
.text-box {
width: 200px;
height: 30px;
padding: 5px;
font-size: 16px;
}
.placeholder-label {
position: absolute;
top: 10px;
left: 10px;
pointer-events: none;
color: #888;
transition: top 0.3s, left 0.3s, font-size 0.3s;
}
.focused {
top: 0px;
left: 5px;
font-size: 12px;
}
.blured {
top: 10px;
left: 10px;
font-size: 16px;
}
</style>
</head>
<body>
<div class="container">
<input type="text" id="myTextBox" class="text-box">
<label for="myTextBox" class="placeholder-label">Enter your text here</label>
</div>
<script>
const textBox = document.getElementById('myTextBox');
textBox.addEventListener('blur', function () {
if (textBox.value.trim() === '') {
placeholderLabel.classList.remove('focused');
placeholderLabel.classList.add('blured');
}
});
const placeholderLabel = document.querySelector('.placeholder-label');
textBox.addEventListener('focus', function () {
placeholderLabel.classList.add('focused');
placeholderLabel.classList.remove('blured');
});
</script>
</body>
</html>
728x90
반응형