CSS/JQuery轮换横幅:实现点击圆圈切换至中间并替换文本
Hey there! I get that this swap functionality has been tricky to nail down—let's break this down into simple, actionable steps to get it working right.
Core Approach
The key here is to track the current center circle and swap both its position (via CSS classes) and content with the clicked outer circle. Here's how to implement it:
Set Up Class-Based Positioning
Make sure your CSS uses distinct classes for the center and outer circles (e.g.,.center-circlefor the middle position,.outer-circlefor the four surrounding spots). This lets us toggle positions just by swapping classes.Add Click Logic with JavaScript
Use JavaScript to listen for clicks on outer circles, then handle the swap:
// Grab all outer circles and the initial center circle const outerCircles = document.querySelectorAll('.outer-circle'); let currentCenterCircle = document.querySelector('.center-circle'); // Attach click event to each outer circle outerCircles.forEach(circle => { circle.addEventListener('click', () => { // Swap position classes to move the circles circle.classList.toggle('center-circle'); circle.classList.toggle('outer-circle'); currentCenterCircle.classList.toggle('center-circle'); currentCenterCircle.classList.toggle('outer-circle'); // Swap text content (adjust this if your text is in a nested element) const tempText = circle.textContent; circle.textContent = currentCenterCircle.textContent; currentCenterCircle.textContent = tempText; // Update our reference to the new center circle currentCenterCircle = circle; }); });
Quick Notes for Your Setup
- If your circles include images along with text, modify the content swap part to target the
<img>tag'ssrcattribute too. For example:// Swap images if needed const tempImgSrc = circle.querySelector('img').src; circle.querySelector('img').src = currentCenterCircle.querySelector('img').src; currentCenterCircle.querySelector('img').src = tempImgSrc; - Add CSS transitions (like
transition: all 0.3s ease;) to the circle classes if you want smooth animation when swapping positions. - Double-check that your initial HTML has the correct classes assigned—one circle with
.center-circle, the rest with.outer-circle.
If you run into snags with specific parts (like layout issues or content not swapping correctly), share more details about your HTML/CSS structure, and we can tweak this further!
内容的提问来源于stack exchange,提问作者WebDevB

