programing

토글 버튼은 어떻게 만드나요?

codeshow 2023. 10. 4. 23:05
반응형

토글 버튼은 어떻게 만드나요?

나는 css를 이용해서 html에 토글 버튼을 만들고 싶습니다.클릭하면 계속 밀어넣고 다시 클릭하면 튀어나오도록 하고 싶어요.

만약 방법이 없다면 그냥 css를 사용해서 할 수 있습니다.jQuery를 이용한 방법이 있습니까?

좋은 의미론적 방법은 체크박스를 사용한 다음 체크박스를 선택하거나 선택하지 않은 경우 다른 방식으로 스타일을 지정하는 것입니다.하지만 좋은 방법은 없습니다.여분의 스판, 여분의 디브, 그리고 정말 멋진 모습을 위해서 자바스크립트를 추가해야 합니다.

따라서 가장 좋은 해결책은 작은 jQuery 기능과 두 개의 배경 이미지를 사용하여 버튼의 두 가지 다른 상태를 스타일링하는 것입니다.테두리에 의해 상향/하향 효과가 부여된 예제:

$(document).ready(function() {
  $('a#button').click(function() {
    $(this).toggleClass("down");
  });
});
a {
  background: #ccc;
  cursor: pointer;
  border-top: solid 2px #eaeaea;
  border-left: solid 2px #eaeaea;
  border-bottom: solid 2px #777;
  border-right: solid 2px #777;
  padding: 5px 5px;
}

a.down {
  background: #bbb;
  border-top: solid 2px #777;
  border-left: solid 2px #777;
  border-bottom: solid 2px #eaeaea;
  border-right: solid 2px #eaeaea;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="button" title="button">Press Me</a>

물론 버튼을 위로, 아래로 나타내는 배경 이미지를 추가하고 배경 색상을 투명하게 만들 수 있습니다.

JQuery UI를 사용하면 토글 버튼을 만들 때 가벼운 작업을 할 수 있습니다.이거 그냥.

<label for="myToggleButton">my toggle button caption</label>
<input type="checkbox" id="myToggleButton" />

당신의 의 신체 에.onLoad아니면 당신의$.ready() 일부 럴)init()아약스 사이트를 구축하는 경우 기능합니다.다음과 같이 JQuery를 삭제합니다.

$("#myToggleButton").button()

()< label for=...>JQueryUI는 토글버튼의 본문에 그것을 사용하기 때문에..)

거기서부터 당신은 다른 사람들처럼 그것을 가지고 일을 합니다.input="checkbox왜냐하면 라고 JQuery UI 는입니다를 합니다.

에 를 가 있습니다.pure css:

  .cmn-toggle {
    position: absolute;
    margin-left: -9999px;
    visibility: hidden;
  }
  .cmn-toggle + label {
    display: block;
    position: relative;
    cursor: pointer;
    outline: none;
    user-select: none;
  }
  input.cmn-toggle-round + label {
    padding: 2px;
    width: 120px;
    height: 60px;
    background-color: #dddddd;
    border-radius: 60px;
  }
  input.cmn-toggle-round + label:before,
  input.cmn-toggle-round + label:after {
    display: block;
    position: absolute;
    top: 1px;
    left: 1px;
    bottom: 1px;
    content: "";
  }
  input.cmn-toggle-round + label:before {
    right: 1px;
    background-color: #f1f1f1;
    border-radius: 60px;
    transition: background 0.4s;
  }
  input.cmn-toggle-round + label:after {
    width: 58px;
    background-color: #fff;
    border-radius: 100%;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
    transition: margin 0.4s;
  }
  input.cmn-toggle-round:checked + label:before {
    background-color: #8ce196;
  }
  input.cmn-toggle-round:checked + label:after {
    margin-left: 60px;
  }
<div class="switch">
  <input id="cmn-toggle-1" class="cmn-toggle cmn-toggle-round" type="checkbox">
  <label for="cmn-toggle-1"></label>
</div>

답변과 함께 모바일 설정 토글러와 같은 스타일을 사용할 수도 있습니다.

togglers

HTML

<a href="#" class="toggler">&nbsp;</a>
<a href="#" class="toggler off">&nbsp;</a>
<a href="#" class="toggler">&nbsp;</a>

CSS

a.toggler {
    background: green;
    cursor: pointer;
    border: 2px solid black;
    border-right-width: 15px;
    padding: 0 5px;
    border-radius: 5px;
    text-decoration: none;
    transition: all .5s ease;
}

a.toggler.off {
    background: red;
    border-right-width: 2px;
    border-left-width: 15px;
}

jQuery

$(document).ready(function(){
    $('a.toggler').click(function(){
        $(this).toggleClass('off');
    });
});

훨씬 더 예쁠 수도 있지만, 아이디어를 줍니다.
은 CSSCSS할 수 입니다.

적절한 버튼을 원한다면 자바스크립트가 필요합니다.이와 같은 것(스타일링에 대한 작업이 필요하지만 요점을 파악합니다.솔직히 말해서 아주 사소한 것에 재키를 사용할 필요는 없습니다.

<html>
<head>
<style type="text/css">
.on { 
border:1px outset;
color:#369;
background:#efefef; 
}

.off {
border:1px outset;
color:#369;
background:#f9d543; 
}
</style>

<script language="javascript">
function togglestyle(el){
    if(el.className == "on") {
        el.className="off";
    } else {
        el.className="on";
    }
}
</script>

</head>

<body>
<input type="button" id="btn" value="button" class="off" onclick="togglestyle(this)" />
</body>
</html>

미니멀리스트 접근 방식의 순수 CSS

배경을 슬라이더로 표시한 확인란만 있으면 됩니다.결과는 키보드에 접근할 수 있습니다.

input {
  appearance: none;
  padding: 16px 32px;
  border-radius: 16px;
  background: radial-gradient(circle 12px, white 100%, transparent calc(100% + 1px)) #ccc -16px;
  transition: 0.3s ease-in-out;
}

:checked {
  background-color: dodgerBlue;
  background-position: 16px;
}
<input type="checkbox">

를 하시면 됩니다.toggleClass()상태를 추적합니다.그런 다음 버튼 요소에 클래스가 있는지 확인합니다. 다음과 같습니다.

$("button.toggler").click( function() {
    $me = $(this);
    $me.toggleClass('off');
    if($me.is(".off")){
        alert('hi');
    }else {
        alert('bye');
    }
});

저는 을 사용합니다.button의미론적인 이유로 버튼에 대한 요소.

<button class="toggler">Toggle me</button>

()를 할 수 .<a></a>및합니다.), a:active a:link 를합니다.생각일 뿐이야.

편집: 위 방법은 토글하기에 너무 잘 작동하지 않습니다.하지만 jquery를 사용할 필요는 없습니다.버튼을 누른 것처럼 배경 이미지를 적절히 변경하는 요소에 대해 간단한 onClick javascript 함수를 작성하고 플래그를 설정합니다.그런 다음 클릭하면 이미지와 플래그가 되돌아옵니다.그렇게

var flag = 0;
function toggle(){
if(flag==0){
    document.getElementById("toggleDiv").style.backgroundImage="path/to/img/img1.gif";
    flag=1;
}
else if(flag==1){
    document.getElementById("toggleDiv").style.backgroundImage="path/to/img/img2.gif";
    flag=0;
}
}

은 html 를 .<div id="toggleDiv" onclick="toggle()">Some thing</div>

저는 당신의 CSS에서 버튼을 누르면 테두리 스타일이나 테두리 폭을 변경하는 클래스를 사용하고 싶어요. 그래서 토글 버튼처럼 보입니다.

JS를 사용하여 버튼을 만드는 것은 좋은 연습이라고 생각하지 않습니다.사용자의 브라우저가 자바스크립트를 비활성화하면 어떻게 됩니까?

그리고 체크박스와 약간의 CSS를 이용해서 할 수 있습니다.또한 체크박스의 상태를 쉽게 검색할 수 있습니다.

이것은 단지 하나의 예시일 뿐이지만 원하는 대로 스타일링 할 수 있습니다.

http://jsfiddle.net/4gjZX/

HTML

<fieldset class="toggle">
  <input id="data-policy" type="checkbox" checked="checked" />
  <label for="data-policy">
  <div class="toggle-button">
    <div class="toggle-tab"></div>
  </div>
  Toggle
  </label>
</fieldset>​

CSS

.toggle label {
  color: #444;
  float: left;
  line-height: 26px;
}
.toggle .toggle-button {
  margin: 0px 10px 0px 0px;
  float: left;
  width: 70px;
  height: 26px;
  background-color: #eeeeee;
  background-image: -webkit-gradient(linear, left top, left bottom, from(#eeeeee), to(#fafafa));
  background-image: -webkit-linear-gradient(top, #eeeeee, #fafafa);
  background-image: -moz-linear-gradient(top, #eeeeee, #fafafa);
  background-image: -o-linear-gradient(top, #eeeeee, #fafafa);
  background-image: -ms-linear-gradient(top, #eeeeee, #fafafa);
  background-image: linear-gradient(top, #eeeeee, #fafafa);
  filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#eeeeee', EndColorStr='#fafafa');
  border-radius: 4px;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border: 1px solid #D1D1D1;
}
.toggle .toggle-button .toggle-tab {
  width: 30px;
  height: 26px;
  background-color: #fafafa;
  background-image: -webkit-gradient(linear, left top, left bottom, from(#fafafa), to(#eeeeee));
  background-image: -webkit-linear-gradient(top, #fafafa, #eeeeee);
  background-image: -moz-linear-gradient(top, #fafafa, #eeeeee);
  background-image: -o-linear-gradient(top, #fafafa, #eeeeee);
  background-image: -ms-linear-gradient(top, #fafafa, #eeeeee);
  background-image: linear-gradient(top, #fafafa, #eeeeee);
  filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#fafafa', EndColorStr='#eeeeee');
  border: 1px solid #CCC;
  margin-left: -1px;
  margin-top: -1px;
  border-radius: 4px;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  -webkit-box-shadow: 5px 0px 4px -5px #000000, 0px 0px 0px 0px #000000;
  -moz-box-shadow: 5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
  box-shadow: 5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
}
.toggle input[type=checkbox] {
  display: none;
}
.toggle input[type=checkbox]:checked ~ label .toggle-button {
  background-color: #2d71c2;
  background-image: -webkit-gradient(linear, left top, left bottom, from(#2d71c2), to(#4ea1db));
  background-image: -webkit-linear-gradient(top, #2d71c2, #4ea1db);
  background-image: -moz-linear-gradient(top, #2d71c2, #4ea1db);
  background-image: -o-linear-gradient(top, #2d71c2, #4ea1db);
  background-image: -ms-linear-gradient(top, #2d71c2, #4ea1db);
  background-image: linear-gradient(top, #2d71c2, #4ea1db);
  filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#2d71c2', EndColorStr='#4ea1db');
}
.toggle input[type=checkbox]:checked ~ label .toggle-button .toggle-tab {
  margin-left: 39px;
  -webkit-box-shadow: -5px 0px 4px -5px #000000, 0px 0px 0px 0px #000000;
  -moz-box-shadow: -5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
  box-shadow: -5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
}​

도움이 되길 바랍니다.

이 부분을 시도해 보십시오.

input type="button" 
                           data-bind="css:{on:toggleButton, off:toggleButton!=true},value:toggleButton,click: function() { $data.toggleButton(!($data.toggleButton()))}" />

in viewModel
self.toggleButton = ko.observable(false);

Swizec의 jquery 플러그인이 있는데, 이것은 무엇보다도 이것을 할 수 있습니다: https://github.com/Swizec/styled-button

(이전 링크는 http://swizec.com/code/styledButton/, 이었습니다. 교체를 완전히 테스트하지는 않았지만 Google에서 찾은 것입니다.)

다음 접근 방식은 html-css에만 의존하므로 어떤 종류의 js도 필요하지 않습니다.

CSS와 HTML 스니펫은 다음과 같이 간단합니다.

#mycbid
{
  display:none;
}

#mycbid:checked + #mylabelid
{
  background: grey;
  border: inset;
}

#mylabelid
{
  background: lightgray;
  border: outset;
}
<input type="checkbox" id="mycbid">
  <label for="mycbid" id="mylabelid">Text of the label</label>

설명:

후드 아래에 확인란이 표시되지는 않지만 선택 또는 선택 해제된 상태로 설정할 수 있으므로 평소와 같이 사용할 수 있습니다.

"트리거"되면 가 "" 의 이 "됩니다. 아래의 CSS 규칙이#mycbid:checked + #mylabelid그에 따라 라벨이 스타일링 될 것입니다.이 css 선택기는 사실 모든 것의 핵심입니다. 사실 확인란의 형제(즉, 라벨 자체)를 선택합니다.확인란이 표시되지 않더라도 레이블은 for 특성 덕분에 확인란으로 클릭을 리디렉션합니다.

되면 가 "" 의 CSS 에 이 실행됩니다.#mylabelid그에 따라 라벨이 스타일링 될 것입니다.

물론 라벨을 다른 방식으로 스타일을 지정하는 것은 가능합니다.

"active" pseudoclass를 사용할 수 있습니다. 링크 이외의 요소의 경우 IE6에서는 작동하지 않습니다.

a:active
{
    ...desired style here...
}

다음은 다음과 같이 jQuery를 사용하여 ToggleButton의 예제/변주(자세히 설명) 중 하나입니다.<label for="input">실행.

먼저 클래식 HTML을 사용하여 ToggleButton을 위한 컨테이너를 만들 것입니다.<input>그리고.<label>

<span>
  <input type="checkbox" value="1" name="some_feature_to_select" id="feature_cb" style="display: none;"> <!-- We can hide checkbox bec. we want <label> to be a ToggleButton, so we don't need to show it. It is used as our value holder -->
  <label for="feature_cb" id="label_for_some_feature">
    <img alt="Stylish image" src="/images/icons/feature.png">
  </label>
</span>

다음으로 버튼을 토글하는 기능을 정의하겠습니다.사실 우리 버튼은 평소와 다름없습니다.<label>가치 토글링을 표현하기 위해 스타일링을 할 것입니다.

function toggleButton(button) {

var _for = button.getAttribute('for'); // defining for which element this label is (suppose element is a checkbox (bec. we are making ToggleButton ;) )
var _toggleID = 'input#'+_for; // composing selector ID string to select our toggle element (checkbox)
var _toggle = $( _toggleID ); // selecting checkbox to work on
var isChecked = !_toggle.is(':checked'); // defining the state with negation bec. change value event will have place later, so we negating current state to retrieve inverse (next).

if (isChecked)
    $(button).addClass('SelectedButtonClass'); // if it is checked -> adding nice class to our button (<label> in our case) to show that value was toggled
else
    $(button).removeClass('SelectedButtonClass'); // if value (or feature) was unselected by clicking the button (<label>) -> removing .SelectedButtonClass (or simply removing all classes from element)
}

기능은 재사용 가능한 방식으로 구현됩니다.작성한 토글 버튼을 하나 이상, 두 개 또는 세 개 이상 사용할 수 있습니다.

... 그리고 마지막으로... 예상대로 작동하려면 토글 함수를 우리의 즉흥적인 이벤트("변경" 이벤트)에 바인딩해야 합니다.<label>button (그렇게 될 것입니다.click이벤트 bec. 우리는 변경하지 않습니다.checkbox단도직입적으로, 그래서 노change이벤트는 다음을 위해 해고될 수 있습니다.<label>).

$(document).ready(function(){

    $("#some_feature_label").click(function () {
        toggleButton(this); // call function with transmitting instance of a clicked label and let the script decide what was toggled and what to do with it
    });

    $("#some_other_feature_label").click(function () {
        toggleButton(this); // doing the same for any other feature we want to represent in a way of ToggleButton
    });

});

CSS를 사용하면 정의할 수 있습니다.backgorund-image또는 어떤border가치의 변화를 나타내는 동안<label>확인란의 값을 변경하는 작업을 수행합니다;).

누군가에게 도움이 되길 바랍니다.

시도;

<li>Text To go with Toggle Button<span class = 'toggle'><input type = 'checkbox' class = 'toggle' name = 'somename' id = 'someid' /></span></li>

그리고 꼭 그 안에.

<head><link rel = 'stylesheet' src = 'theme.css'> (from jqtouch - downloadable online)
      <link rel = 'text/javascript' src = 'jquery.js'> (also from jqtouch)
</head>

이 코드를 코드화할 만 기억하십시오. somename그리고.someid입력 태그가 변경될 수 있습니다. 그렇지 않으면 작동하지 않습니다.

저도 답을 찾고 있어서 CSS로 해보고 싶었습니다.. CSS NINJA다의 입니다. 그것은 좋은 구현입니다. 구현입니다.<input type="checkbox">CSS 라이브 데모도 있고요.IE 8에서는 작동하지 않지만 사용하는 곳에서 selectivizr!을 구현하고 CSS를 수정할 수 있습니다.opacity.filterIE에서 작동되도록 하기 위해서입니다.

편집 2014:

새로운 토글 버튼의 경우 iOS와 시각적으로 유사한 Lea Verou 블로그에서 찾은 솔루션을 사용합니다.

@Mori의 탁월한 미니멀리스트 CSS 전용 답변의 "사각 코너" 버전은 다음과 같습니다.

enter image description here

.switch {
  appearance: none;
  height: 30px;
  width: 52px;
  background-image: linear-gradient(to bottom, transparent 0 22px, dodgerBlue 22px), 
                    linear-gradient(to right, white 0 22px, dodgerBlue 22px 60px);
  transition: 0.2s ease-in-out;
  background-position: 4px 4px;
}
.switch:checked {
  background-position: 26px 4px;
}
<input type="checkbox" class="switch">

그리고 파란색 면이 두 개인 원형(회색 면 비활성화 없음):

.switch {
  appearance: none;
  padding: 16px 30px;
  border-radius: 16px;
  background: radial-gradient(circle 12px, white 100%, transparent calc(100% + 1px)) dodgerBlue -14px;
  transition: 0.3s ease-in-out;
}

.switch:checked {
  background-position: 14px;
}
<input type="checkbox" class="switch">

언급URL : https://stackoverflow.com/questions/309081/how-do-you-create-a-toggle-button

반응형