我仍然是 CSS
和 Javascript
的初学者。我尝试使用 CSS 和 JavaScript 制作一个 carousel
。
我想知道如何为自定义轮播上的点创建逻辑?
我创建了按钮,他们正在努力传递幻灯片。但是你能告诉我如何创建这些点吗?
这是我在 codesandbox 中的项目
export function usePosition(ref) {
const [prevElement, setPrevElement] = React.useState(null);
const [nextElement, setNextElement] = React.useState(null);
React.useEffect(() => {
const element = ref.current;
const update = () => {
const rect = element.getBoundingClientRect();
const visibleElements = Array.from(element.children).filter((child) => {
const childRect = child.getBoundingClientRect();
return rect.left <= childRect.left && rect.right >= childRect.right;
});
if (visibleElements.length > 0) {
setPrevElement(getPrevElement(visibleElements));
setNextElement(getNextElement(visibleElements));
}
};
update();
element.addEventListener("scroll", update, { passive: true });
return () => {
element.removeEventListener("scroll", update, { passive: true });
};
}, [ref]);
const scrollToElement = React.useCallback(
(element) => {
const currentNode = ref.current;
if (!currentNode || !element) return;
let newScrollPosition;
newScrollPosition =
element.offsetLeft +
element.getBoundingClientRect().width / 2 -
currentNode.getBoundingClientRect().width / 2;
console.log("newScrollPosition: ", newScrollPosition);
currentNode.scroll({
left: newScrollPosition,
behavior: "smooth"
});
},
[ref]
);
const scrollRight = React.useCallback(() => scrollToElement(nextElement), [
scrollToElement,
nextElement
]);
return {
hasItemsOnLeft: prevElement !== null,
hasItemsOnRight: nextElement !== null,
scrollRight,
scrollLeft
};
}
在此先感谢您的帮助!!
答案 0 :(得分:-1)
您会在下面找到我的解决方案,我从沙箱中取出您的代码并使用它。我不明白您是否想显示点,滚动和同步点并单击点以更改图像,所以我做了所有这些。 codesandbox