选择时更改背景

我正在尝试引导程序,但似乎卡住了。我有一些单选按钮,但我想要的是在未选择时勾勒出轮廓,并在选择时显示为实心或“btn-primary”。


我可以尝试用 JavaScript 来做机智,但我可能必须给每个人一个单独的 ID,然后从那里开始。我确信 JavaScript 有更好的方法


        <div class="row">

            <div class="col offset-md-2">

                <div class="form-group">

                    <div class="btn-group">

                        <button type="button" class="btn btn-outline-secondary" id="zone1">Zone 1</button>

                        <button type="button" class="btn btn-outline-secondary" id="zone2">Zone 2</button>

                        <button type="button" class="btn btn-outline-secondary" id="zone3">Zone 3</button>

                        <button type="button" class="btn btn-outline-secondary" id="zone4">Zone 4</button>

                        <button type="button" class="btn btn-outline-secondary" id="zone5">Zone 5</button>

                        <button type="button" class="btn btn-outline-secondary" id="zone6">Zone 6</button>

                        <button type="button" class="btn btn-outline-secondary" id="bush">Bush</button>

                    </div>      

                </div>

            </div>

        </div>


凤凰求蛊
浏览 155回答 2
2回答

茅侃侃

如果您想使用纯 JavaScript 实现这一点,您可以为每个元素绑定一个点击处理程序。单击按钮时,处理程序将修改元素的类:var buttons = document.getElementsByTagName("button");for (var i = 0; i < buttons.length; i++) {&nbsp; &nbsp;&nbsp;buttons[i].onclick = function() {&nbsp; &nbsp; this.classList.remove('btn-outline-secondary');&nbsp; &nbsp; this.classList.add('btn-primary');&nbsp;}}.btn-outline-secondary {border: 1px solid #aaa;}.btn-primary {border: 1px solid blue; background: blue; color: white;}<div class="row">&nbsp; <div class="col offset-md-2">&nbsp; &nbsp; <div class="form-group">&nbsp; &nbsp; &nbsp; <div class="btn-group">&nbsp; &nbsp; &nbsp; &nbsp; <button type="button" class="btn btn-outline-secondary" id="zone1">Zone 1</button>&nbsp; &nbsp; &nbsp; &nbsp; <button type="button" class="btn btn-outline-secondary" id="zone2">Zone 2</button>&nbsp; &nbsp; &nbsp; &nbsp; <button type="button" class="btn btn-outline-secondary" id="zone3">Zone 3</button>&nbsp; &nbsp; &nbsp; &nbsp; <button type="button" class="btn btn-outline-secondary" id="zone4">Zone 4</button>&nbsp; &nbsp; &nbsp; &nbsp; <button type="button" class="btn btn-outline-secondary" id="zone5">Zone 5</button>&nbsp; &nbsp; &nbsp; &nbsp; <button type="button" class="btn btn-outline-secondary" id="zone6">Zone 6</button>&nbsp; &nbsp; &nbsp; &nbsp; <button type="button" class="btn btn-outline-secondary" id="bush">Bush</button>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>&nbsp; </div></div>有关在没有框架的情况下绑定事件和更改元素类的更多信息,请参阅这两个答案。替代如果您愿意使用诸如 jQuery 之类的库,那么绑定事件处理程序可能会简单得多。包含 jQuery 库后,您的代码将是:$("button").click(function(){ /*apply new class using .removeClass() and .addClass() methods*/ });有关.click() 的更多信息,请参阅jQuery 文档。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript