write a beautiful search input and Clear content using js full code
Here's an example of a beautiful search input with clear content button using JavaScript:
HTML:
<div class="search-container">
<input type="text" id="search-input" placeholder="Search...">
<button id="clear-button" aria-label="Clear search input">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm4.2 15.8l-1.4 1.4L12 13.4l-2.8 2.8-1.4-1.4L10.6 12 7.8 9.2l1.4-1.4L12 10.6l2.8-2.8 1.4 1.4L13.4 12l2.8 2.8z"/>
</svg>
</button>
</div>
CSS:
.search-container {
position: relative;
}
#search-input {
width: 100%;
padding: 12px 16px;
border: none;
border-radius: 20px;
background-color: #f2f2f2;
font-size: 16px;
color: #333;
outline: none;
}
#search-input:focus {
background-color: #fff;
box-shadow: 0 0 0 2px #007bff;
}
#clear-button {
position: absolute;
top: 50%;
right: 16px;
transform: translateY(-50%);
background: none;
border: none;
cursor: pointer;
outline: none;
opacity: 0.5;
transition: opacity 0.2s ease-in-out;
}
#clear-button:hover {
opacity: 1;
}
#clear-button svg {
width: 24px;
height: 24px;
fill: #333;
}
JavaScript:
const searchInput = document.getElementById('search-input');
const clearButton = document.getElementById('clear-button');
searchInput.addEventListener('input', () => {
clearButton.style.display = searchInput.value !== '' ? 'block' : 'none';
});
clearButton.addEventListener('click', () => {
searchInput.value = '';
searchInput.focus();
clearButton.style.display = 'none';
});
In this example, the search input has a rounded border and a gray background. When the user types in the search input, a clear button appears on the right side of the input. The clear button is hidden by default and only appears when the search input has a value. When the user clicks the clear button, the search input is cleared and the focus is returned to the input.
原文地址: https://www.cveoy.top/t/topic/B0K 著作权归作者所有。请勿转载和采集!