code

토글 버튼은 어떻게 만듭니 까?

codestyles 2020. 8. 28. 07:30
반응형

토글 버튼은 어떻게 만듭니 까?


CSS를 사용하여 html로 토글 버튼을 만들고 싶습니다. 나는 당신이 그것을 클릭 할 때 밀린 상태로 유지되고 다시 클릭 할 때보 다 튀어 나오도록하고 싶습니다.

CSS를 사용하는 방법이 없다면. jQuery를 사용하여 수행하는 방법이 있습니까?


좋은 의미 론적 방법은 확인란을 사용한 다음 선택 여부에 따라 다른 방식으로 스타일을 지정하는 것입니다. 하지만 좋은 방법은 없습니다. 당신은 여분의 스팬, 여분의 div를 추가하고, 정말 멋진 모습을 위해 자바 스크립트를 추가해야합니다.

따라서 가장 좋은 해결책은 버튼의 두 가지 상태를 스타일링하기 위해 작은 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()ajax 사이트를 구축하는 경우 일부 객체 리터럴 기능 ..) 다음과 같이 일부 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>


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

토글 러

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');
    });
});

훨씬 더 예뻐질 수 있지만 아이디어를 제공합니다.
한 가지 장점은 jquery 및 / 또는 CSS3 Fiddler 로 애니메이션 할 수 있다는 것입니다.


적절한 버튼을 원하면 자바 스크립트가 필요합니다. 이와 같은 것 (스타일링에 대한 작업이 필요하지만 요점을 얻습니다). 솔직히 말해서 너무 사소한 일에 jquery를 사용하는 것을 귀찮게하지 않을 것입니다.

<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>

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를 사용하는 것은 좋은 습관이라고 생각하지 않습니다. 사용자의 브라우저가 JavaScript를 비활성화하면 어떻게됩니까?

또한 체크 박스와 약간의 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;
}​

도움이 되었기를 바랍니다


Try this bit:

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);

There's a jquery plugin by Swizec, which can do this among other things: https://github.com/Swizec/styled-button

(The old link was http://swizec.com/code/styledButton/, I didn't fully test the replacement, just found it w/Google.)


You can use the "active" pseudoclass (it won't work on IE6, though, for elements other than links)

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

Here is one of the example/variant (more detail described) of ToggleButton using jQuery with <label for="input"> implementation.

1st we will create container for our ToggleButton using classic HTML <input> and <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>

Next we will define function for toggling our button. Our button actually is the usual <label> which we will be styling to represent value toggling.

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)
}

Function is implemented in a reusable way. You can use it for more than one, two or even three ToggleButtons you've created.

... and finally ... to make it work as expected, we should bind toggle function to an event ("change" event) of our improvised <label> button (it will be click event bec. we are not altering the checkbox directly, so no change event can be fired for <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
    });

});

With CSS we can define backgorund-image or some border to represent the change in value whilst <label> will do the job for us in altering the value of a checkbox ;).

Hope this helps someone.


Try;

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

And make sure in the

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

Remember when you are coding this, only somename and someid can change in the input tag, otherwise it doesn't work.


내가 대답을 찾고 있었고 CSS로 완성하고 싶었습니다. 나는 CSS NINJA의 해결책을 찾았습니다. 그것은 멋진 구현 <input type="checkbox">과 CSS 라이브 데모입니다 ! IE 8에서는 작동하지 않지만 selectivizr을 구현할 수 있습니다 ! IE에서 작동하도록 사용 opacity하는 CSS를 수정 filter합니다.

2014 년 수정 :

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

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

반응형