CSS를 사용하여 html로 토글 버튼을 만들고 싶습니다. 나는 당신이 그것을 클릭 할 때 밀린 상태로 유지되고 다시 클릭 할 때보 다 튀어 나오도록하고 싶습니다.
CSS를 사용하는 방법이 없다면. jQuery를 사용하여 수행하는 방법이 있습니까?
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"> </a>
<a href="#" class="toggler off"> </a>
<a href="#" class="toggler"> </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>
앵커 요소 ( <a></a>)를 사용하고 a : active 및 a : link를 사용하여 배경 이미지를 켜거나 끌 수 있습니다. 그냥 생각.
편집 : 위의 방법은 토글에 너무 잘 작동하지 않습니다. 그러나 jquery를 사용할 필요는 없습니다. 버튼이 눌린 것처럼 보이도록 배경 이미지를 적절하게 변경하는 요소에 대한 간단한 onClick 자바 스크립트 함수를 작성하고 플래그를 설정합니다. 그런 다음 다음 클릭시 이미지와 플래그가 되돌아갑니다. 그렇게
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>
버튼을 만들기 위해 JS를 사용하는 것은 좋은 습관이라고 생각하지 않습니다. 사용자의 브라우저가 JavaScript를 비활성화하면 어떻게됩니까?
또한 체크 박스와 약간의 CSS 만 사용하면됩니다. 체크 박스의 상태를 쉽게 검색 할 수 있습니다.
이것은 하나의 예일 뿐이지 만 원하는대로 스타일을 지정할 수 있습니다.
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;
}
도움이 되었기를 바랍니다
Swizec 의 jquery 플러그인이 있습니다.이 플러그인은 무엇보다도 다음 과 같이 할 수 있습니다 : https://github.com/Swizec/styled-button
(이전 링크는 http://swizec.com/code/styledButton/ , 교체를 완전히 테스트하지 않고 Google에서 찾았습니다.)
"활성"가상 클래스를 사용할 수 있습니다 (링크 이외의 요소에 대해서는 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)
}
기능은 재사용 가능한 방식으로 구현됩니다. 생성 한 하나, 둘 또는 세 개 이상의 ToggleButton에 사용할 수 있습니다.
... 그리고 마지막으로 ... 예상대로 작동하도록하려면 즉석 <label>버튼 의 이벤트 ( "변경"이벤트)에 토글 기능을 바인딩해야 합니다 ( click이벤트 전일 것입니다. 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>있으며 체크 박스의 값을 변경하는 작업을 수행합니다.).
이것이 누군가를 돕기를 바랍니다.
.addClass()/ 대신 .removeClass()사용할 수 .toggleClass()있지만 설명 된 메서드는 checked/ unchecked값에 대한 작업을 명시 적으로 정의 합니다.
시험;
<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을 구현할 수 있습니다 ! IE에서 작동하도록 사용 opacity하는 CSS를 수정 filter합니다.
2014 년 수정 :
새로운 토글 버튼의 경우 iOS 확인란과 시각적으로 유사한 Lea Verou 블로그 에서 찾은 솔루션을 사용합니다.