效果图
鼠标悬停时文字滚动,当文字详情长度不足撑满父元素时,不会滚动。
组件代码
其中的--s
表示动画时间,根据文字详情长度和容器宽度得出,文字越长,动画时间也就越长,不然文字滚动的会很快。
<script lang="tsx">
import { onMounted, ref, defineComponent, nextTick, computed } from "vue";
export default defineComponent({
name: "xxxAre",
props: {
text: {
type: [Number, String],
default: "",
},
},
setup(props) {
const text = computed({
get() {
return props.text;
},
set() {},
});
let needToScroll = ref(false);
const innerRef = ref<HTMLSpanElement | null>(null);
const outerRef = ref<HTMLSpanElement | null>(null);
const outerWidth = ref(0);
const innerWidth = ref(0);
const isOverflow = () => {
outerWidth.value = outerRef.value!.offsetWidth;
innerWidth.value = innerRef.value!.offsetWidth;
needToScroll.value = innerWidth.value > outerWidth.value;
};
onMounted(() => {
nextTick(() => {
isOverflow();
});
});
return () => (
<div class={"box"]} ref={outerRef}>
<div
class={[needToScroll.value ? "scrolling" : "", "inner"]}
style={[
`--s:${innerWidth.value / outerWidth.value < 3 ? "5s" : innerWidth.value / outerWidth.value < 6 ? "10s" : "15s"}`,
]}
>
<span class={"scrolling__section", "pr-25"]} ref={innerRef}>
{text.value}
</span>
{needToScroll.value && (
<span class={"scrolling__section", "pr-25"]}>{text.value}</span>
)}
</div>
</div>
);
},
});
</script>
<style lang="scss" scoped>
.box {
width: 100%;
margin-bottom: 5px;
overflow: hidden;
white-space: nowrap;
@keyframes scroll {
0% {
transform: translate3d(0%, 0, 0);
}
100% {
transform: translate3d(-50%, 0, 0);
}
}
.section {
padding(0 5px);
}
.scrolling {
//注释的部分,如果需要超出部分显示省略号就打开
// width: 100%;
// text-overflow: ellipsis;
// overflow: hidden;
// white-space: nowrap;
}
.inner {
display: inline-block;
}
&:hover .scrolling {
// overflow: visible !important;
animation: scroll var(--s) linear infinite;
}
}
</style>
父组件
正常引入组件
<xxxAre text="显示的文字显示的文字显示的文字显示的文字!!!" />