前端vue点击一个按钮慢慢画出一条横竖线,并且两条线连在一起
时间: 2024-05-06 12:19:49 浏览: 5
可以使用Vue.js的动画功能来实现这个效果。
首先,在模板中定义一个按钮和两条线的容器:
```html
<template>
<div>
<button @click="drawLine">Draw Line</button>
<div class="line-container">
<div class="horizontal-line" ref="horizontalLine"></div>
<div class="vertical-line" ref="verticalLine"></div>
</div>
</div>
</template>
```
然后,在样式中定义容器和线条的样式:
```css
.line-container {
position: relative;
width: 200px;
height: 200px;
border: 1px solid black;
margin: 20px;
}
.horizontal-line, .vertical-line {
position: absolute;
background-color: black;
height: 1px;
width: 0;
transition: width 1s ease;
}
.horizontal-line {
top: 50%;
left: 0;
}
.vertical-line {
top: 0;
left: 50%;
}
```
接下来,在Vue组件中定义一个方法来触发动画,并获取两条线的DOM元素:
```js
export default {
methods: {
drawLine() {
// 获取两条线的DOM元素
const horizontalLine = this.$refs.horizontalLine;
const verticalLine = this.$refs.verticalLine;
// 触发动画
horizontalLine.style.width = '100%';
verticalLine.style.height = '100%';
}
}
}
```
这里使用了CSS的`transition`属性来实现线条慢慢画出的效果。当按钮被点击时,将两条线的宽度和高度设置为100%,触发动画效果。
最后,可以在两条线的样式中添加一个`::after`伪元素,使它们连在一起:
```css
.horizontal-line::after, .vertical-line::after {
content: '';
position: absolute;
top: 0;
left: 100%;
height: 1px;
width: 20px;
background-color: black;
}
```
这样就可以实现一个点击按钮慢慢画出一条横竖线,并且两条线连在一起的效果了。