programing

아이폰처럼 HTML 텍스트 입력 상자에 클리어 버튼을 넣으려면 어떻게 해야 합니까?

skycolor 2023. 6. 1. 22:37
반응형

아이폰처럼 HTML 텍스트 입력 상자에 클리어 버튼을 넣으려면 어떻게 해야 합니까?

클릭하면 <INPUT> 상자의 텍스트가 지워지는 멋진 작은 아이콘을 원합니다.

이는 입력 상자 외부에 명확한 링크를 두는 대신 공간을 절약하기 위한 것입니다.

제 CSS 실력은 약합니다...여기 있습니다. 스크린샷 아이폰이 어떻게 보이는지에 대한 사진.

오늘날요소를 사용하면 매우 간단합니다.

<input type="search" placeholder="Search..."/>

지원되는 브라우저는 기본적으로 필드에서 사용 가능한 지우기 단추를 자동으로 렌더링합니다.

일반 HTML5 검색 입력 필드

지우기 버튼은 웹킷/블링크 기반 브라우저에 의해 자동으로 삽입되는 CSS 유사 요소입니다(기술적으로는 여전히 비표준 기능임에도 불구하고).


부트스트랩을 사용하는 경우 CSS 오버라이드를 추가하여 유사 요소를 강제로 표시해야 합니다.

input[type=search]::-webkit-search-cancel-button {
    -webkit-appearance: searchfield-cancel-button;
}

부트스트랩 검색 입력 필드


공식적으로 psuedo-element는 비표준이므로 브라우저 전체에 내장된 HTML 기능으로 의존해서는 안 됩니다.

특히 Firefox는 버전 110에서 기본적으로 지우기 버튼을 렌더링하지 않지만 나중에 활성화할 계획입니다. https://bugzilla.mozilla.org/show_bug.cgi?id=1654288 .MDN 또는 Can에서 최신 브라우저 호환성 정보를 확인할 수 있습니다.IUse.com .

가장 안정적이고 미래에 대비한 교차 브라우저 접근 방식은 버튼으로 검색 양식을 지울 수 있도록 근처에 명시적 요소가 있는 양식을 사용하는 것입니다.이것은 또한 접근성 힌트를 추가하고 CSS로 직접 지우기 버튼을 스타일화하는 것을 더 쉽게 만듭니다.

<form action="/search">
  <input type="search" placeholder="Search..."/>
  <input type="reset" value="X" alt="Clear the search form">
  <input type="submit" value="Search">
</form>

수동 입력 재설정 버튼이 추가된 검색


추가 기능: Safari/WebKit 브라우저는 사용 시 추가 기능을 제공할 수도 있습니다.type="search",맘에 들다results=5,enterkeyhint="...",그리고.autosave="..."그러나 키, 테두리와 같은 많은 스타일을 덮어씁니다.이러한 오버라이드를 방지하기 위해 X 버튼과 같은 기능을 유지하면서 CSS에 다음을 추가할 수 있습니다.

input[type=search] {
    -webkit-appearance: none;
}

에서 제공하는 기능에 대한 자세한 최신 정보는 MDN 설명서, CanIUse.com 또는 CSS-Tricks.com 를 참조하십시오.<input type="search"/>오늘날 브라우저에서.

부터 HTML5를할 수 있게 .<input type="search">그러나 이것이 반드시 사용자 지정이 가능한 것은 아닙니다.UI를 완전히 제어하고 싶은 경우 두 가지 킥오프 예제가 있습니다.jQuery가 있는 것과 없는 것.

jQuery 사용:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 2803532</title>
        <script src="https://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).ready(function() {
                $('input.deletable').wrap('<span class="deleteicon"></span>').after($('<span>x</span>').click(function() {
                    $(this).prev('input').val('').trigger('change').focus();
                }));
            });
        </script>
        <style>
            span.deleteicon {
                position: relative;
                display: inline-flex;
                align-items: center;
            }
            span.deleteicon span {
                position: absolute;
                display: block;
                right: 3px;
                width: 15px;
                height: 15px;
                border-radius: 50%;
                color: #fff;
                background-color: #ccc;
                font: 13px monospace;
                text-align: center;
                line-height: 1em;
                cursor: pointer;
            }
            span.deleteicon input {
                padding-right: 18px;
                box-sizing: border-box;
            }
        </style>
    </head>
    <body>
        <input type="text" class="deletable">
    </body>
</html>

jQuery 사용 안 함

jQuery는 엄격하게 필요하지 않습니다. 점진적인 향상에 필요한 논리를 소스와 잘 구분할 뿐입니다. 물론 일반 HTML/CSS/JS도 사용할 수 있습니다.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 2803532, with "plain" HTML/CSS/JS</title>
        <style>
            span.deleteicon {
                position: relative;
                display: inline-flex;
                align-items: center;
            }
            span.deleteicon span {
                position: absolute;
                display: block;
                right: 3px;
                width: 15px;
                height: 15px;
                border-radius: 50%;
                color: #fff;
                background-color: #ccc;
                font: 13px monospace;
                text-align: center;
                line-height: 1em;
                cursor: pointer;
            }
            span.deleteicon input {
                padding-right: 18px;
                box-sizing: border-box;
            }
        </style>
    </head>
    <body>
        <span class="deleteicon">
            <input type="text">
            <span onclick="var input = this.previousElementSibling; input.value = ''; input.focus();">x</span>
        </span>
    </body>
</html>

더 못생긴 HTML(및 비크로스 브라우저 호환 JS ;)만 표시됩니다.

다시 말하지만 UI 모양이 가장 큰 문제가 아니지만 기능이 중요하다면 그냥 사용하십시오.<input type="search">대신에<input type="text">HTML5 지원 브라우저에 (브라우저별) 지우기 버튼이 표시됩니다.

HTML5는 당신이 원하는 것을 할 수 있다고 생각하는 '검색' 입력 유형을 소개합니다.

<input type="search" />

여기 실제 사례가 있습니다.

jQuery-ClearSearch 플러그인을 확인하십시오.이것은 구성 가능한 jQuery 플러그인입니다. 입력 필드를 스타일링하여 필요에 맞게 조정하는 것은 간단합니다.다음과 같이 사용하면 됩니다.

<input class="clearable" type="text" placeholder="search">

<script type="text/javascript">
    $('.clearable').clearSearch();
</script>

안타깝게도 실제로 텍스트 상자 안에 넣을 수는 없고 안에 있는 것처럼 만들 뿐입니다. 이는 안타깝게도 일부 CSS가 필요하다는 것을 의미합니다.p

이론은 입력을 div로 감싸고 입력에서 모든 테두리와 배경을 제거한 다음 div를 상자처럼 보이도록 스타일을 지정합니다.그런 다음 코드의 입력 상자 뒤에 버튼을 누르면 작업이 잘 수행됩니다.

어쨌든 그것이 작동하게 되면 ;)

물론 가장 좋은 방법은 더욱 강력한 지원을 제공하는<input type="search" />.

어쨌든 약간의 코딩 재미로 저는 양식의 재설정 버튼을 사용하여 달성할 수 있다고 생각했습니다. 그리고 이것이 작업 결과입니다(양식에 다른 입력을 가질 수 없지만 이 접근 방식을 사용하는 검색 필드를 사용하거나 재설정 버튼을 사용하여 해당 입력을 지울 수 있습니다). Javascript가 필요하지 않습니다.

form{
    position: relative;
    width: 200px;
}

form input {
    width: 100%;
    padding-right: 20px;
    box-sizing: border-box;
}

form input:placeholder-shown + button{
  opacity: 0;
  pointer-events: none;
} 

form button {
    position: absolute;
    border: none;
    display: block;
    width: 15px;
    height: 15px;
    line-height: 16px;
    font-size: 12px;
    border-radius: 50%;
    top: 0;
    bottom: 0;
    right: 5px;
    margin: auto;
    background: #ddd;
    padding: 0;
    outline: none;
    cursor: pointer;
    transition: .1s;
}
<form>
        <input type="text" placeholder=" " />
        <button type="reset">&times;</button>
</form>

저는 당신이 찾고 있는 것 같은 창의적인 해결책이 있습니다.

$('#clear').click(function() {
  $('#input-outer input').val('');
});
body {
  font-family: "Tahoma";
}
#input-outer {
  height: 2em;
  width: 15em;
  border: 1px #e7e7e7 solid;
  border-radius: 20px;
}
#input-outer input {
  height: 2em;
  width: 80%;
  border: 0px;
  outline: none;
  margin: 0 0 0 10px;
  border-radius: 20px;
  color: #666;
}
#clear {
  position: relative;
  float: right;
  height: 20px;
  width: 20px;
  top: 5px;
  right: 5px;
  border-radius: 20px;
  background: #f1f1f1;
  color: white;
  font-weight: bold;
  text-align: center;
  cursor: pointer;
}
#clear:hover {
  background: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input-outer">
  <input type="text">
  <div id="clear">
    X
  </div>
</div>

https://jsfiddle.net/qdesign/xn9eogmx/1/

Firefox가 검색 필드 지우기 기능을 지원하지 않는 것 같습니다...저는 잘 작동하는 순수한 CSS 솔루션을 찾았습니다.CSS | Codepen | 2013에서 완전한 버튼이 있는 텍스트 상자.마법은 에서 일어납니다.

.search-box:not(:valid) ~ .close-icon {
    display: none;
}

body {
    background-color: #f1f1f1;
    font-family: Helvetica,Arial,Verdana;

}
h2 {
    color: green;
    text-align: center;
}
.redfamily {
    color: red; 
}
.search-box,.close-icon,.search-wrapper {
    position: relative;
    padding: 10px;
}
.search-wrapper {
    width: 500px;
    margin: auto;
}
.search-box {
    width: 80%;
    border: 1px solid #ccc;
  outline: 0;
  border-radius: 15px;
}
.search-box:focus {
    box-shadow: 0 0 15px 5px #b0e0ee;
    border: 2px solid #bebede;
}
.close-icon {
    border:1px solid transparent;
    background-color: transparent;
    display: inline-block;
    vertical-align: middle;
  outline: 0;
  cursor: pointer;
}
.close-icon:after {
    content: "X";
    display: block;
    width: 15px;
    height: 15px;
    position: absolute;
    background-color: #FA9595;
    z-index:1;
    right: 35px;
    top: 0;
    bottom: 0;
    margin: auto;
    padding: 2px;
    border-radius: 50%;
    text-align: center;
    color: white;
    font-weight: normal;
    font-size: 12px;
    box-shadow: 0 0 2px #E50F0F;
    cursor: pointer;
}
.search-box:not(:valid) ~ .close-icon {
    display: none;
}
<h2>
    Textbox with a clear button completely in CSS <br> <span class="redfamily">< 0 lines of JavaScript ></span>
</h2>
<div class="search-wrapper">
    <form>
    <input type="text" name="focus" required class="search-box" placeholder="Enter search term" />
        <button class="close-icon" type="reset"></button>
    </form>
</div>

더 많은 기능이 필요했고 코드에 이 jQuery를 추가했습니다.

$('.close-icon').click(function(){ /* my code */ });

이 간단한 솔루션은 다음과 같은 이점을 제공합니다.

<input type="text" id="myInput" value="No War"/><button onclick="document.getElementById('myInput').value = ''" title="Clear">X</button></input>

@마흐무드 알리 카셈

조금 전에 CSS를 다르게 보이게 변경하고 포커스()를 추가했습니다.

https://jsfiddle.net/xn9eogmx/81/

$('#clear').click(function() {
  $('#input-outer input').val('');
  $('#input-outer input').focus();
});
body {
  font-family: "Arial";
  font-size: 14px;
}
#input-outer {
  height: 2em;
  width: 15em;
  border: 1px #777 solid;
  position: relative;
  padding: 0px;
  border-radius: 4px;
}
#input-outer input {
  height: 100%;
  width: 100%;
  border: 0px;
  outline: none;
  margin: 0 0 0 0px;
  color: #666;
  box-sizing: border-box;
  padding: 5px;
  padding-right: 35px;
  border-radius: 4px;
}
#clear {
  position: absolute;
  float: right;
  height: 2em;
  width: 2em;
  top: 0px;
  right: 0px;
  background: #aaa;
  color: white;
  text-align: center;
  cursor: pointer;
  border-radius: 0px 4px 4px 0px;
}
#clear:after {
  content: "\274c";
  position: absolute;
  top: 4px;
  right: 7px;
}
#clear:hover,
#clear:focus {
  background: #888;
}
#clear:active {
  background: #666;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input-outer">
  <input type="text">
  <div id="clear"></div>
</div>

HTML5에서는 매우 간단합니다.

<input type="search">

이것이 당신의 일이 될 것입니다!

언급URL : https://stackoverflow.com/questions/2803532/how-do-i-put-a-clear-button-inside-my-html-text-input-box-like-the-iphone-does

반응형