使用iCheck jQuery插件时,勾选单选框后如何滚动到指定div?
Hey there! I see you're using the iCheck jQuery plugin to style your radio buttons, and you want to trigger an automatic scroll to a specific div when a particular radio is checked. Let's make that work—here's how:
Since iCheck replaces native input elements with custom markup, we need to use iCheck's own events (not the standard change event) to detect when the radio is checked. Let's walk through the setup step by step.
Step 1: Confirm your target div exists
First, make sure you have the div you want to scroll to with a unique ID. For example:
<div id="target-section">This is the section we'll scroll to!</div>
Step 2: Update your iCheck script
Modify your existing script to add a listener for the ifChecked event on your specific radio button, then trigger the scroll. Here's the full updated code:
Your Radio Button (unchanged):
<input type="radio" class="checkb" name="selectplan" value="P6302" id="P6302">
Updated Script:
$(document).ready(function () { // Initialize iCheck styling $('input').iCheck({ checkboxClass: 'icheckbox_square-red', radioClass: 'iradio_square-red', increaseArea: '20%' // optional }); // Add scroll trigger for the P6302 radio button $('#P6302').on('ifChecked', function() { // Smooth scroll to the target div (replace #target-section with your actual ID) $('html, body').animate({ scrollTop: $('#target-section').offset().top }, 500); // 500ms = scroll speed—adjust to make it faster/slower // Alternative: Native smooth scroll (no jQuery animate needed) // document.getElementById('target-section').scrollIntoView({ behavior: 'smooth' }); }); });
Key Details to Note:
- iCheck Event Usage:
ifCheckedis the correct event to listen for with iCheck-styled inputs—this ensures we detect the check action even though the original input is hidden by the plugin's custom markup. - Scroll Customization: The jQuery
animatemethod creates a smooth scroll effect; tweak the500value to adjust the speed. If you prefer native browser behavior, use the commented-outscrollIntoViewline instead. - Target ID: Don't forget to replace
#target-sectionwith the actual ID of the div you want to scroll to.
That's all! Now when someone checks the P6302 radio button, the page will smoothly scroll to your target section.
内容的提问来源于stack exchange,提问作者Mahdi Mobasheri

