如何延迟5-10分钟或按页面访问次数显示Bootstrap Cookie Alert?
Absolutely! You can repurpose that Bootstrap cookie alert into a fully functional page rating form, and add both delay-based display (5-10 minutes) and visit-count-based triggers using vanilla JavaScript (no extra libraries needed). Let's walk through the changes step by step:
Step 1: Modified HTML (Rating Form Alert)
First, we'll swap out the cookie message content for a rating UI, keeping the Bootstrap alert structure intact for styling consistency:
<div id="rating-alert" data-expire="30" class="alert alert-primary alert-position-bottom" style="display: none;"> <div class="container"> <button type="button" class="close" id="rating-close-btn"> <span class="cookie-close-btn" aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <p class="fs-13 mb-2"> <i class="fa fa-star"></i> How did you like our page? Let us know! </p> <!-- Star Rating Component --> <div class="rating-stars mb-3"> <i class="fa fa-star-o rating-star" data-rating="1"></i> <i class="fa fa-star-o rating-star" data-rating="2"></i> <i class="fa fa-star-o rating-star" data-rating="3"></i> <i class="fa fa-star-o rating-star" data-rating="4"></i> <i class="fa fa-star-o rating-star" data-rating="5"></i> <input type="hidden" id="selected-rating" value="0"> </div> <button type="button" class="btn btn-sm btn-success" id="submit-rating">Submit Rating</button> </div> </div>
We added:
- Hidden initial state (
style="display: none") so we can trigger it later - Clickable star rating icons
- Hidden input to store the selected rating
- Submit button for the rating
Step 2: JavaScript for Triggers & Functionality
Add this script right before your closing </body> tag to handle both delay and visit count triggers, plus rating submission logic:
document.addEventListener('DOMContentLoaded', function() { const ratingAlert = document.getElementById('rating-alert'); const closeBtn = document.getElementById('rating-close-btn'); const submitBtn = document.getElementById('submit-rating'); const ratingStars = document.querySelectorAll('.rating-star'); const selectedRatingInput = document.getElementById('selected-rating'); // Helper to store user preference (prevents repeated alerts) function setRatingCompleted() { localStorage.setItem('ratingCompleted', 'true'); // Match expiration from original data-expire attribute (days) const expireDays = ratingAlert.dataset.expire; const expireDate = new Date(); expireDate.setDate(expireDate.getDate() + parseInt(expireDays)); localStorage.setItem('ratingExpire', expireDate.toUTCString()); } // Check if rating was already completed (or not expired yet) const ratingCompleted = localStorage.getItem('ratingCompleted'); const ratingExpire = localStorage.getItem('ratingExpire'); if (ratingCompleted === 'true' && (!ratingExpire || new Date() < new Date(ratingExpire))) { return; // Skip showing alert if user already interacted } // --- Trigger 1: Delay Display (5-10 minutes) --- const delayMinutes = 5; // Adjust to 10 for 10-minute delay const delayMs = delayMinutes * 60 * 1000; // --- Trigger 2: Visit Count (Show after N visits) --- let visitCount = parseInt(localStorage.getItem('pageVisitCount')) || 0; visitCount++; localStorage.setItem('pageVisitCount', visitCount); const triggerAfterVisits = 3; // Show after 3 page visits // Show alert function function showRatingAlert() { ratingAlert.style.display = 'block'; } // Check which trigger to use if (visitCount >= triggerAfterVisits) { showRatingAlert(); } else { // Use delay if visit count hasn't been met setTimeout(showRatingAlert, delayMs); } // Star rating click handler ratingStars.forEach(star => { star.addEventListener('click', function() { const rating = parseInt(this.dataset.rating); selectedRatingInput.value = rating; // Update star visuals ratingStars.forEach((s, index) => { if (index < rating) { s.classList.remove('fa-star-o'); s.classList.add('fa-star'); } else { s.classList.remove('fa-star'); s.classList.add('fa-star-o'); } }); }); }); // Close button handler closeBtn.addEventListener('click', function() { ratingAlert.style.display = 'none'; setRatingCompleted(); }); // Submit button handler submitBtn.addEventListener('click', function() { const rating = selectedRatingInput.value; if (rating > 0) { // Replace this with your actual submission logic (e.g., send to API) console.log('Submitted rating:', rating); ratingAlert.style.display = 'none'; setRatingCompleted(); // Optional: Show thank you message alert('Thank you for your feedback!'); } else { alert('Please select a rating first!'); } }); });
Key Features Explained:
- Dual Triggers: The alert shows immediately if the user has visited the page
3times (adjusttriggerAfterVisits), otherwise it waits5minutes (adjustdelayMinutes) - Persistent State: Uses
localStorageto remember if the user already submitted/closed the alert, so it won't reappear until the 30-day expiration period - Interactive Rating: Clickable stars that update visually and store the selected rating
- Bootstrap Compatibility: Keeps the original alert styling to match your existing theme
Quick Customization Tips:
- Tweak
delayMinutesto set the delay (5-10 minutes as requested) - Change
triggerAfterVisitsto adjust how many page visits are required - Swap the alert class (
alert-primary) to change the color scheme (e.g.,alert-warning,alert-info) - Replace the
console.login the submit handler with your actual API call to save the rating
内容的提问来源于stack exchange,提问作者Denis Evseev
相关产品推荐
相关产品推荐

