【问题标题】:How do I create the dots on my custom carousel?如何在自定义轮播上创建点?
【发布时间】:2021-04-26 22:40:44
【问题描述】:

我还是 CSSJavascript 的初学者。我尝试使用 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
  };
}

提前感谢您的帮助!!

【问题讨论】:

    标签: javascript css reactjs carousel


    【解决方案1】:

    您将在下面找到我的解决方案,我从沙箱中获取了您的代码并使用它。我不明白您是否想显示点,滚动和同步点并单击点以更改图像,所以我做了所有这些。 codesandbox

    【讨论】:

      猜你喜欢
      • 2011-10-08
      • 2023-03-29
      • 1970-01-01
      • 2020-01-16
      • 2021-05-16
      • 2020-02-14
      • 2021-08-12
      • 1970-01-01
      相关资源
      最近更新 更多