如何使用bootstrap组按钮构建“切换开关”?一个在另一个是关闭,反之亦然

时间:2018-05-26 17:45:37

标签: javascript html bootstrap-4

我需要两个按钮(这些按钮用于在两个可折叠的div之间进行切换),这些按钮默认关闭,如果其中一个打开,另一个(如果之前打开)将关闭。我正在使用当前版本的bootstrap.min.css和bootstrap.min.js以及我编写的JavaScript文件:

 $('#1kgbtn').on('click', function () {
 $('#25kgpack').collapse('hide')
 if ($('#25kgbtn').button('active') == true) {
   $('#25kgbtn').button('toggle')
 }
 else {}
 })
 $('#25kgbtn').on('click', function () {
 $('#1kgpack').collapse('hide')
 if ($('#1kgbtn').button('active') == true) {
   $('#1kgbtn').button('toggle')
 }
 else {}
 })

我的html代码如下所示:

<div class="btn-group btn-group-toggle" data-toggle="buttons">
 <button class="btn btn-outline-primary" id="1kgbtn" type="button" data-toggle="collapse" data-target="#1kgpack" aria-expanded="false" aria-controls="collapseExample" aria-pressed="false" autocomplete="off">
  1kg package
</button>

<button class="btn btn-outline-primary" id="25kgbtn" type="button" data-toggle="collapse" data-target="#25kgpack" aria-expanded="false" aria-controls="collapseExample" aria-pressed="false" autocomplete="off">
  2.5kg package
</button>
</div>

但是我编写的JavaScript无法正常工作,只有折叠部分可以工作,按钮切换不起作用。

(我不想使用收音机,因为这不适用于折叠,至少对我不好)

感谢您的期待

2 个答案:

答案 0 :(得分:0)

如果我正确理解了这个问题,你只想在不使用单选按钮的情况下切换按钮类似于单选按钮。

您可以在引导脚本下面设置此代码,以在读取后取消文件中的任何默认值。从上到下读取Html,因此您的文件看起来像这样。

使用你的代码我添加了类&#34; remove-active&#34;两个按钮和removeClass到你的javascript。你做得对,你只需要特朗普的默认行动。默认情况下,一旦切换需要被重新调整以保持活动状态。

   <div class="btn-group btn-group-toggle" data-toggle="buttons">
     <button class="btn btn-outline-primary remove-active" id="1kgbtn" type="button" data-toggle="collapse" data-target="#1kgpack" aria-expanded="false" aria-controls="collapseExample" aria-pressed="false" autocomplete="off">
      1kg package
    </button>

    <button class="btn btn-outline-primary remove-active" id="25kgbtn" type="button" data-toggle="collapse" data-target="#25kgpack" aria-expanded="false" aria-controls="collapseExample" aria-pressed="false" autocomplete="off">
      2.5kg package
    </button>
</div>

 <script src="bootstrap.min.js"></script>

    <script>
$('#1kgbtn').on('click', function () {


        $('#25kgpack').collapse('hide')

        $('.remove-active').removeClass('active');

        if ($('#25kgbtn').button('active') == true) {
            $('#1kgbtn').button('toggle');
        }       
 });

 $('#25kgbtn').on('click', function () {

        $('#1kgpack').collapse('hide');
     $('.remove-active').removeClass('active');

     if ($('#1kgbtn').button('active') == true) {
         $('#25kgbtn').button('toggle');
    }
});
</script>

使用数据目标,您可以获取ID并稍后使用它执行不同的操作。 (这部分只是因为它很酷)

    $('button[data-toggle="collapse"]').click(function(){
    //log the id of the target
    console.log($(this).attr('data-target'));        
});

我希望这会有所帮助。

- 编辑 -

我对代码进行了一些修改,但发表了评论以帮助解释。

            //on button click

        $('button').click(function(e){
            //the current button is toggled

            //check to see if the other button is toggled

            if($('.remove-active').hasClass('active')){ //if it has class this means it is active
                //store the active id
                var e = $('.remove-active.active').attr('id');

                //we clicked on the same button then we would equal the same id
                    if(e == $(this).attr('id')){
                        //collapse the clicked Id if we are unpressing the button
                        $(this).collapse('hide');

                        console.log(e + ' auto toggles with bootstrap and collapse the currently clicked target ' + $(this).attr('data-target'));                       

                       }else{ // else
                           //we untoggle the other button and element
                           $('#' + e).button('toggle');
                           //we also collapse the other element
                           $($('#' + e).attr('data-target')).collapse('hide');

                           console.log("The other element was clicked and we cleared it along with collapsing the " + $('#' + e).attr('data-target'));
                       }                        
               }

            //be sure to close out the console.log() stuff
            //this is just for viewing example
        });

这将切换当前按钮,检查是否切换了另一个按钮,如果是,则切换它。此外,如果按钮被切换,则在点击该按钮时,所述按钮然后被取消。

答案 1 :(得分:0)

我通过删除data-toggle属性并使用Javascript切换来解决此问题。每个按钮调用toggleBtnActiveState函数并向其传递两个参数:

1)点击按钮的ID。
2)隐藏的div的ID

<button type="button" 
        id="dvdBtn"
        name="dvdBtn"  
        class="extra-attrib-btn btn btn-outline-info btn-default mx-1"
        onclick="toggleBtnActiveState('dvdBtn', 'dvdInput')">
  DVD
</button>

<button type="button" 
        id="bookBtn"
        name="bookBtn" 
        class="extra-attrib-btn btn btn-outline-info btn-default mx-1"
        onclick="toggleBtnActiveState('bookBtn', 'bookInput')">
  Book
</button>

<button type="button" 
        id="furnitureBtn"
        name="furnitureBtn" 
        class="extra-attrib-btn btn btn-outline-info btn-default mx-1"
        onclick="toggleBtnActiveState('furnitureBtn', 'furnitureInput')">
 Furniture
</button>

JavaScript函数的工作方式如下:

function toggleBtnActiveState(buttonId, divId)
{
    activeButton = document.getElementById(buttonId);

    hiddenDivs = document.querySelectorAll('.hidden-div');
    btns = document.querySelectorAll('.extra-attrib-btn');

    //Remove .active class for each btn
    Array.prototype.forEach.call(btns, function(btn)
    {
        removeClass(btn, 'active');
    })

    //Collapsable div show/hide logic
    Array.prototype.forEach.call(hiddenDivs, function(div) 
    {

        //If hidden div matches selected btn and is visible, hide it and selected btn active class
        if (div.id == divId && hasClass(div, 'show')) {
            removeClass(div, 'show');
            removeClass(activeButton, 'active');
            return;
        }
        // If it matches but is not visible, show it and btn active class
        if (div.id == divId && !hasClass(div, 'show'))
        {
            addClass(div, 'show');
            addClass(activeButton, 'active')
            return;
        }

        //This gets called if previous two statements are not, and removes visibility of the div
        if (hasClass(div, 'show')) {
            removeClass(div, 'show');

        }
    })
}

助手类:

function hasClass(el, className) {
    if (el.classList)
        return el.classList.contains(className)
    else
        return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
}

function addClass(el, className) {
    if (el.classList)
        el.classList.add(className)
    else if (!hasClass(el, className)) el.className += " " + className
}

function removeClass(el, className) {
    if (el.classList)
        el.classList.remove(className)
    else if (hasClass(el, className)) {
        var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
        el.className = el.className.replace(reg, ' ')
    }
}