【问题标题】:Make div onclick event work instead of buttons and checkboxes inside it?使 div onclick 事件而不是其中的按钮和复选框起作用?
【发布时间】:2020-11-07 13:14:09
【问题描述】:

我有一个 div 里面有一个复选框,而复选框本身不能工作(它是由 div onclick 触发的),我想让它点击 div 上的任意位置(包括复选框,或按钮,div 的 onclick 事件被调用而不是按钮/复选框)。有点像 z-index 但用于 javascript?

【问题讨论】:

  • 所以你正在重塑标签
  • @epascarello 但是当我使用标签时,单击复选框也可以,这里复选框被禁用,这就是为什么我希望触发 div 的 onclick 事件
  • 为什么复选框被禁用我不明白@SomeName?您可以使用标签+复选框组合元素轻松完成此操作。如果您需要代码方面的帮助,请在帖子上回复。
  • 你可能想要做的是避免复选框触发的事件,尝试通过css指针事件禁用它:无;
  • @SomeName 你不需要这个<div class="dabba">,换成label 并删除p

标签: javascript html css


【解决方案1】:

使用标签

.product {
  display: inline-block;
  width: 100px;
  height: 100px;
  margin: 5px;
}

.product label {
  display: block;
  width: 100%;
  height: 100%;
  border: 1px solid black;
  cursor: pointer;
}
<div class="product">
  <label><span>Product 1</span>
  <input type="checkbox" id="p1" />
  </label>
</div>

<div class="product">
  <label><span>Product 2</span>
  <input type="checkbox" id="p2" />
  </label>
</div>

<div class="product">
  <label><span>Product 3</span>
  <input type="checkbox" id="p3" />
  </label>
</div>

另一种变化

.product {
  display: inline-block;
  width: 100px;
  height: 100px;
  margin: 5px;
}

.product input {
  display: none;
}

.product label {
  display: block;
  width: 100%;
  height: 100%;
  border: 1px solid black;
  cursor: pointer;
}

.product input:checked + label {
  background-color: #CCC;
}
<div class="product">
  <input type="checkbox" id="p1" />
  <label for="p1">Product 1</label>
</div>

<div class="product">
  <input type="checkbox" id="p2" />
  <label for="p2">Product 2</label>
</div>

<div class="product">
  <input type="checkbox" id="p3" />
  <label for="p3">Product 3</label>
</div>

【讨论】:

    【解决方案2】:

    您可能想要做的是避免复选框触发的事件,尝试通过 css pointer-events: none; 禁用它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-18
      • 2014-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      • 2018-10-12
      • 1970-01-01
      相关资源
      最近更新 更多