【问题标题】:How I keep clicked button light up till I click another button?在单击另一个按钮之前,如何保持单击的按钮亮起?
【发布时间】:2016-09-15 15:07:56
【问题描述】:

我即将制作一排按钮作为菜单栏,我希望它们的行为符合我的意愿。所以假设有按钮ABCD。例如,如果我单击按钮B,我希望它亮起并保持亮起,直到我单击另一个按钮(ACD)。这种想法。我很确定这不是新的。而且我相信有比我下面的版本更复杂的方法来做到这一点。 我还希望每次单击按钮时页面都会滚动。

$('#abutton').click(function() {
    $('#abutton').removeClass('off').addClass('on');
    $('#bbutton').removeClass('on').addClass('off');
    $('#cbutton').removeClass('on').addClass('off');
    $('#dbutton').removeClass('on').addClass('off');
    window.scrollTo(0,0);
});

$('#bbutton').click(function() {
    $('#abutton').removeClass('on').addClass('off');
    $('#bbutton').removeClass('off').addClass('on');
    $('#cbutton').removeClass('on').addClass('off');
    $('#dbutton').removeClass('on').addClass('off');
    window.scrollTo(0,0);
});

$('#cbutton').click(function() {
    $('#abutton').removeClass('on').addClass('off');
    $('#bbutton').removeClass('on').addClass('off');
    $('#cbutton').removeClass('off').addClass('on');
    $('#dbutton').removeClass('on').addClass('off');
    window.scrollTo(0,0);
});

$('#dbutton').click(function() {
    $('#abutton').removeClass('on').addClass('off');
    $('#bbutton').removeClass('on').addClass('off');
    $('#cbutton').removeClass('on').addClass('off');
    $('#dbutton').removeClass('off').addClass('on');
    window.scrollTo(0,0);
});

【问题讨论】:

  • 能否提供html
  • html 很简单。按钮是在点击时改变颜色的文本。带有开和关的 CSS 类。
  • 它实际上是按钮、div、span 还是其他东西?
  • 类似这个jsfiddle的东西? jsfiddle.net/ns7e5hyt
  • 谢谢哥们。这个 jsfiddle 非常完美。我把它弄得太复杂了。

标签: javascript jquery button click


【解决方案1】:

使用类

$('.button').click(function(){
    $('.button').removeClass('on').addClass('off');
    $(this).addClass('on').removeClass('off');
});

fiddle

【讨论】:

  • 就这么简单。您只是忘记从$(this) 中删除off。你也可以输入$('.button').removeClass('on').addClass('off'); 并用两行来解决它。
【解决方案2】:

一个好主意是为所有按钮添加一些类。例如.btn

$(".btn").on("click", function(){ 
    $(".btn").removeClass("on").addClass("off");
    $(this).removeClass("off").addClass("on"); 
});

如果所有按钮都在某个父级中,则代码更简单。

$(".btn").on("click", function(){ 
    $(this).removeClass("off").addClass("on").siblings().removeClass("on").addClass("off");
});

$(".btn").on('click', function(){ 
    $(this).removeClass("off").addClass("on").siblings().removeClass("on").addClass("off"); 
});
button.on { 
    background: yellow; 
    color: #000; 
}
button.off { 
    background: gray; 
    color: #fff; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="abutton" class="btn">button a</button>
<button id="bbutton" class="btn">button b</button>
<button id="cbutton" class="btn">button c</button>
<button id="dbutton" class="btn">button d</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多