<template>
<div v-if="show" class="command-code" :style="{ color: color }">
<div class="command-code-box" ref="boxRef" :style="{ width: contentWidth }">
<span
ref="contentRef"
class="command-code-content"
@mouseenter="cursorEnter"
@mouseleave="cursorLeave"
>
{{ content }}
</span>
</div>
</div>
</template>
<script setup>
const props = defineProps({
show: {
type: Boolean,
default: false
},
content: {
type: String,
default: '内容'
},
delay: { // 动画延迟时间
type: Number,
default: 1000
},
space: { // 每次移动的距离
type: Number,
default: 5
},
color: {
type: String,
default: '#27CBF3'
}
});
const boxRef = ref(null);
const contentRef = ref(null);
const boxWidth = ref('');
const contentWidth = ref('');
const timer = ref(null); // 定时器
function textCarousel() {
nextTick(() => {
let left = 0;
if (boxRef.value && contentRef.value) {
boxWidth.value = boxRef.value?.offsetWidth;
contentWidth.value = contentRef.value?.offsetWidth;
if (contentWidth.value > boxWidth.value) { // 内容溢出则滚动展示
cursorEnter();
timer.value = setInterval(() => {
// 一次向左移动的距离
left -= props.space;
// 当左移超过这个宽度时,重新设置left
if (left <= -contentWidth.value) {
left = 0;
}
contentRef.value.style.left = left + "px";
}, props.delay);
}
}
});
}
// 鼠标进入,停止定时器
function cursorEnter() {
timer.value && clearInterval(timer.value);
}
// 鼠标离开,继续定时器
function cursorLeave() {
textCarousel();
}
watch(() => props.show, () => {
if (props.show) {
textCarousel();
} else {
cursorLeave();
}
});
</script>
<style lang="scss" scoped>
.command-code {
position: absolute;
top: 0.4rem;
left: 6.7rem;
width: 2.8rem;
height: 0.54rem;
padding: 0 0.2rem;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.16rem;
font-weight: 600;
color: #27CBF3;
background: url(@/assets/map_images/code-bg.png) no-repeat 50%;
background-size: 100% 100%;
}
.command-code-box {
width: 100%;
overflow: hidden;
white-space: nowrap;
text-align: center;
.command-code-content {
position: relative;
}
}
</style>