body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
margin: 0;
}
.input-container {
position: relative;
}
.cursor {
position: absolute;
width: 2px;
background-color: black;
height: 24px;
animation: blink 1s infinite;
}
@keyframes blink {
0% {
opacity: 1;
}
50% {
opacity: 0;
}
100% {
opacity: 1;
}
}
<template>
<div class="input-container">
<van-field
v-model="inputValue"
readonly
@click="showKeyboard"
ref="fieldRef"
placeholder="Click to enter numbers"
/>
<div
class="cursor"
v-if="true"
:style="{ left: cursorLeft + 'px', top: cursorTop + 'px' }"
></div>
<van-number-keyboard
v-model:show="keyboardVisible"
@input="handleInput"
@delete="handleDelete"
@blur="handleBlur"
/>
</div>
</template>
<script>
import { ref, nextTick } from "vue";
export default {
setup() {
const inputValue = ref("");
const keyboardVisible = ref(false);
const showCursor = ref(false);
const cursorLeft = ref(0);
const cursorTop = ref(0);
const cursorIndex = ref(0);
const fieldRef = ref(null);
const showKeyboard = () => {
keyboardVisible.value = true;
updateCursorPosition();
};
const handleInput = (value) => {
const beforeCursor = inputValue.value.slice(0, cursorIndex.value);
const afterCursor = inputValue.value.slice(cursorIndex.value);
inputValue.value = beforeCursor + value + afterCursor;
cursorIndex.value++;
updateCursorPosition();
};
const handleDelete = () => {
if (cursorIndex.value > 0) {
const beforeCursor = inputValue.value.slice(0, cursorIndex.value - 1);
const afterCursor = inputValue.value.slice(cursorIndex.value);
inputValue.value = beforeCursor + afterCursor;
cursorIndex.value--;
updateCursorPosition();
}
};
const handleBlur = () => {
keyboardVisible.value = false;
showCursor.value = false;
};
const updateCursorPosition = () => {
nextTick(() => {
console.log(fieldRef.value)
console.log(' cursorIndex.value:', cursorIndex.value)
const fieldElement = fieldRef.value?.$el.querySelector("input");
if (fieldElement) {
const fieldRect = fieldElement.getBoundingClientRect();
cursorLeft.value = cursorIndex.value * 14; // Adjust the multiplier as needed
// cursorTop.value = fieldRect.top + 8; // Adjust the top position as needed
showCursor.value = true;
}
});
};
return {
inputValue,
keyboardVisible,
showCursor,
cursorLeft,
cursorTop,
cursorIndex,
fieldRef,
showKeyboard,
handleInput,
handleDelete,
handleBlur,
updateCursorPosition,
};
},
};
</script>
<style src="./assets/reset.css"></style>
5152

被折叠的 条评论
为什么被折叠?



