这份文档中提到,按钮可以被设置为开关模式,但是给出的示例仅为:
<div class="ui toggle button">
Vote
</div>
很自然地,这不起作用。检查示例的源代码会发现一个active
类是通过编程方式添加的。
我可能错过了一些简单的东西,但我该怎么创建一个像示例中那样的切换按钮?指定要切换的内容的语法是什么?
semantic.button = {};
// ready event
semantic.button.ready = function() {
// selector cache
var
$buttons = $('.ui.buttons .button'),
$toggle = $('.main .ui.toggle.button'),
$button = $('.ui.button').not($buttons).not($toggle),
// alias
handler = {
activate: function() {
$(this)
.addClass('active')
.siblings()
.removeClass('active')
;
}
}
;
$buttons
.on('click', handler.activate)
;
$toggle
.state({
text: {
inactive : 'Vote',
active : 'Voted'
}
})
;
};
// attach ready event
$(document)
.ready(semantic.button.ready)
;
semantic = {};
,否则这将无法工作。你会得到 ReferenceError: Can't find variable: semantic
。为什么不包括 semantic = {};
? - iconoclast$('.ui.button.toggle').state();
这应该在单击时在默认的灰色和绿色之间切换颜色。查看其他答案以获取更复杂的行为。请确保DOM等已加载,就像其他Semantic UI初始化程序一样。
<script src="components/state.js"></script>
我必须从语义组件中包含state js - https://github.com/Semantic-Org/Semantic-UI-CSS/blob/master/components/state.js。或者使用 state.min.js
。这似乎是最合适的答案,因为它使用语义API,而不是使用非语义代码来实现相同的效果。 - Sahil Singh这非常简单,
<button class="ui toggle button active" id="tgl">Toogle button</button>
只需使用经典的 jQuery click 方法来切换 active 类,并添加其他所需更改。我认为在这种情况下使用语义化标记是浪费时间。
$('#tgl').click(function(){
$(this).toggleClass('active');
});
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="../../dist/semantic.css">
<script src="../assets/library/jquery.min.js"></script>
<script src="../../dist/semantic.js"></script>
</head>
<script>
function show(b){
alert( $(b).hasClass("active"));
}
// attach ready event
$(document)
.ready(function() {
var $toggle = $('.ui.toggle.button');
$toggle
.state({
text: {
inactive : 'Vote',
active : 'Voted'
}
})
;
})
;
</script>
<body>
<button class="ui toggle button" onclick="show(this)">
Vote
</button>
<br/><br/>
<button class="ui toggle button" onclick="show(this)">
Vote
</button>
</body>
</html>