Svelte中实现卡片点击跳转但复选框点击不触发的方案
Got it, let's sort out this issue—you want clicking the Card to navigate to another page, but clicking the Checkbox inside it should only trigger its own action, not the navigation. The key here is stopping the click event from bubbling up from the Checkbox to the parent Card element, and we can handle this cleanly inside your Checkbox component.
Solution 1: Stop Propagation on the Checkbox's Label
Since your Checkbox component wraps everything in a <label> (which is the right approach for accessibility!), adding the stopPropagation modifier directly to the label will block all click events from bubbling up to the Card. Here's how to modify your Checkbox component:
// Checkbox Component <label on:keypress={handleEnter} tabindex="1" class="checkbox-holder" {style} on:click|stopPropagation <!-- Add this line --> > <input type="checkbox" bind:checked /> <div class="cool-checkbox"> <div class="checkbox-square" class:checkbox-square-active={checked}> <i class={`fal fa-${checked ? 'check' : 'minus'}`} /> </div> <span>{label}</span> </div> </label>
This works because any click on the label (whether it's the checkbox input, the icon, or the label text) will have its event stopped before it reaches the parent Card's on:click handler. Perfect for keeping the Checkbox's actions isolated.
Solution 2: Stop Propagation Only on the Input (Less Ideal)
If you specifically want clicks on the label text to still trigger the Card's navigation (though this might confuse users), you can apply the modifier only to the input element instead:
<input type="checkbox" bind:checked on:click|stopPropagation />
But I'd recommend Solution 1—users expect the entire checkbox area (including the label text) to be part of the checkbox interaction, not the card navigation.
Why Your Previous Attempts Didn't Work
When you tried using self or stopPropagation on the Card element, it likely failed because the click event's target was the Checkbox's input/label, not the Card itself. The self modifier only triggers the handler if the event originates directly on the Card div, which doesn't happen when clicking the Checkbox. Stopping propagation at the source (the Checkbox component) is the most reliable approach here.
内容的提问来源于stack exchange,提问作者Gh05d

