以下是使用Vue3实现文字滚动的示例:

HTML:

<template>
  <div class="scroll-container">
    <div class="scroll-text" ref="scrollText">{{ text }}</div>
  </div>
</template>

CSS:

.scroll-container {
  width: 300px;
  height: 50px;
  overflow: hidden;
}

.scroll-text {
  white-space: nowrap;
  font-size: 20px;
  animation: marquee 10s linear infinite;
}

@keyframes marquee {
  0%   { transform: translateX(0); }
  100% { transform: translateX(-100%); }
}

JavaScript:

<script>
import { ref, onMounted } from 'vue';

export default {
  name: 'ScrollText',
  props: {
    text: {
      type: String,
      required: true
    }
  },
  setup(props, { refs }) {
    const scrollText = ref(null);
    
    onMounted(() => {
      const containerWidth = scrollText.value.parentNode.offsetWidth;
      const textWidth = scrollText.value.offsetWidth;
      
      if (textWidth > containerWidth) {
        scrollText.value.style.animationDuration = `${textWidth / 50}s`;
      }
    });
    
    return {
      scrollText
    };
  }
};
</script>

使用:

<template>
  <ScrollText text="这是要滚动的文字" />
</template>

<script>
import ScrollText from './ScrollText.vue';

export default {
  name: 'App',
  components: {
    ScrollText
  }
};
</script>

在上面的示例中,我们创建了一个名为ScrollText的组件,它接受一个名为text的prop,表示要滚动的文字。我们在组件的模板中创建了一个包含滚动文字的div,并为其添加了一个ref属性,以便我们可以在JavaScript中引用它。

在组件的JavaScript部分,我们使用了Vue3中的ref和onMounted函数创建了一个名为scrollText的响应式引用。在onMounted生命周期钩子中,我们获取了滚动文字的容器和文本的宽度,并根据它们的大小来计算动画的持续时间。

最后,在App组件中,我们可以像这样使用ScrollText组件:

<template>
  <ScrollText text="这是要滚动的文字" />
</template>

<script>
import ScrollText from './ScrollText.vue';

export default {
  name: 'App',
  components: {
    ScrollText
  }
};
</script>
用vue3实现文字滚动

原文地址: http://www.cveoy.top/t/topic/beKX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录