html
<div style="display: flex; align-items: center;">
<input id="kw" type="text" >
<button id="clearBtn" onclick="clearText()" style="display: none;">X</button>
</div>
css
#kw {
width: 300px;
height: 34px;
padding: 5px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 4px 0 0 4px;
}
#clearBtn {
width: 14px;
height: 14px;
margin: 10px 10px 10px -24px;
font-size: 12px;
border: none;
cursor: pointer;
opacity: 0.6;
transition: opacity 0.3s ease;
}
#clearBtn:hover {
opacity: 1;
}
javascript
function clearText() {
document.getElementById("kw").value = "";
document.getElementById("clearBtn").style.display = "none";
}
document.getElementById("kw").addEventListener("input", function() {
var clearBtn = document.getElementById("clearBtn");
if (this.value.trim() !== "") {
clearBtn.style.display = "inline";
} else {
clearBtn.style.display = "none";
}
});