javascript - 将复选框更改为开关样式按钮

标签 javascript jquery css angularjs

我正在尝试将我的复选框更改为开关样式。该复选框使用 ng-repeat 呈现。问题是,当我单击任何开关样式的复选框时,只有顶部的复选框发生变化。

出了什么问题?

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.records = [
    "John Doe",
    "Tom Jones",
    "James Riley",
    "Ted Mandy",
  ]
});
input[type=checkbox] {
  height: 0;
  width: 0;
  visibility: hidden;
}

label {
  cursor: pointer;
  text-indent: -9999px;
  width: 60px;
  height: 23px;
  background: grey;
  display: block;
  border-radius: 100px;
  position: relative;
}

label:after {
  content: '';
  position: absolute;
  top: 5px;
  left: 5px;
  width: 18px;
  height: 12px;
  background: #fff;
  border-radius: 90px;
  transition: 0.3s;
}

input:checked+label {
  background: #bada55;
}

input:checked+label:after {
  left: calc(100% - 5px);
  transform: translateX(-100%);
}

label:active:after {
  width: 130px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.5.4/css/mdb.min.css" rel="stylesheet">

<body ng-app="myApp" ng-controller="myCtrl">
  <table>
    <tr>
      <th>Names</th>
      <th>Tick</th>
    </tr>
    <tr ng-repeat="x in records">
      <td>{{x}}</td>
      <td> <input type="checkbox" id="switch" />
        <label for="switch"></label></td>
    </tr>
  </table>
</body>

View at w3schools.com

最佳答案

您还没有将重复的复选框输入绑定(bind)到任何模型。

此外,您正在重复使用相同的 id 值。

考虑扩展您的 records 模型,使其也包含复选框的事件状态。

<tr ng-repeat="record in records">
    <td>{{ record.name }}</td>
    <td>
        <input type="checkbox" id="switch{{ $index }} ng-model="record.active"  />
        <label for="switch{{ $index }}"></label>
    </td>
</tr>

...

$scope.records = [
    { name: "John Doe", active: false },
    { name: "Tom Jones", active: false },
    { name: "James Riley", active: false },
    { name: "Ted Mandy", active: false },
];

Modified version of your example.

关于javascript - 将复选框更改为开关样式按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52304091/

相关文章:

javascript - HTML/JavaScript/CSS : Change a picture by clicking on it

jquery - 过滤自定义选择器是否大于 jQuery 中的数字

javascript - 如何在 Handlebars 模板中使用西类牙语字符

javascript - 如何更改现有脚本中的字体颜色?

javascript - 元素未检测到单击事件

javascript - jQuery 简单计算不工作,不显示任何错误

javascript - React router 1.0.0-beta3 无法正常工作

javascript异步/等待不工作

css - 当父级有 css 动画时 z-index 丢失

css - 可以溢出 : hidden; work with inline-blocks?