javascript - 使用 DIV 创建我自己的类似单选按钮?

标签 javascript html

我正在尝试创建一个网站,用户可以在其中创建自己的社交网络按钮。 (我知道它已经完成,但主要是为了练习)。该网站的一部分将允许用户选择按钮的形状。这是 HTML:

<div class="design" id="shape">
  <div class="shapeSelect square" id="square"></div>
  <div class="shapeSelect rounded" id="rounded"></div>
  <div class="shapeSelect circle" id="circle"></div>
</div>

我想做的是在单击 div 时添加一个事件监听器。单击后,类属性将更改为“选定”。当单击另一个时,第一个单击的将被清除,并选择下一个。就像单选按钮一样。

我熟悉 JavaScript,我的想法是这样的:

    window.onload = function () {
    'use strict';
    document.getElementById("square").addEventListener('click', function (e) {//adds the event listener
       divArray = document.getElementById("shape");//Here is my first issue: an array is not returned
       if (!(document.getElementById("square").getAttribute("class") == "shapeSelect square selected")) {// checks to make sure its not already selected
            for (i = 0, count = document.getElementById("shape").length; i < count; i++) {// if it isn't go through the array
                divArray[i]// and this is where i also get stuck. I Can't figure out how i would return the class attribute to be class="shapeSelect circle" instead of class="shapeSelect circle selected"
            };
        }
    }, false);
}

最佳答案

scdavis41 答案的更简单版本:

$(document).ready(function(){  
  $('#shape > .shapeSelect').click(function(){
    $('#shape > .shapeSelect').removeClass('selected');
    $(this).addClass('selected');
  });
});

我还放置了一个选择器,其中包含控件的主 div id,以防您想在页面中多次放置此控件。

** 编辑 **

如果您绝对想使用 javascript 和 DOM,请尝试以下操作:

document.getElementById("square").addEventListener('click', function (e) {
    var divArray = document.getElementById("shape").getElementsByTagName("div"); //Get all the div child element of the main div

    for (i = 0, count = divArray.length; i < count; i++) {
        if(divArray[i].getAttribute("class").indexOf("selected") !== -1) { //check if the selected class is contained in the attribute
            divArray[i].setAttribute("class", divArray[i].getAttribute("class").replace("selected", "")); // clear the selected class from the attribute
        }
    };

    document.getElementById("square").setAttribute("class", document.getElementById("square").getAttribute("class").concat(" selected")); //select the square
}, false);

关于javascript - 使用 DIV 创建我自己的类似单选按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17867895/

相关文章:

javascript - Href 标题属性在 IE10 中不起作用

html - 如何通过标题文本获得图片

position - 跨度被强制显示为 block

ruby-on-rails-3 - Ruby On Rails 与 HTML5 和 CSS3

javascript - 如何使用正则表达式解析Javascript中某种格式的字符串?

php - 如何离线使用谷歌地图从 mysql 数据库映射位置?

javascript - jQuery 最接近的方法不起作用

javascript - 正在对动态子项进行排序的 Lit 元素

html - 从桌面浏览器到移动浏览器的莫名其妙的字体大小变化

html - Bootstrap 4 Forms With 2 Columns(动态)