Tailwind CSS 和 Vue.js 实现按钮点击切换高亮
以下是一个使用 Tailwind CSS 和 Vue.js 实现多个按钮点击切换高亮的案例:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Button Highlight Example</title>
<link href='https://cdn.jsdelivr.net/npm/tailwindcss@2.1.1/dist/tailwind.min.css' rel='stylesheet'>
</head>
<body class='bg-gray-200'>
<div id='app' class='container mx-auto p-4'>
<div class='flex'>
<button
v-for='(button, index) in buttons'
:key='index'
:class='{ 'bg-blue-500 text-white': button.isActive, 'bg-gray-300': !button.isActive }'
class='px-4 py-2 mr-2 rounded'
@click='toggleButton(index)'
>
{{ button.label }}
</button>
</div>
</div>
<script src='https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js'></script>
<script>
new Vue({
el: '#app',
data: {
buttons: [
{ label: 'Button 1', isActive: false },
{ label: 'Button 2', isActive: false },
{ label: 'Button 3', isActive: false },
]
},
methods: {
toggleButton(index) {
this.buttons[index].isActive = !this.buttons[index].isActive;
}
}
});
</script>
</body>
</html>
在上面的案例中,我们使用 Vue 的 v-for 指令循环渲染按钮,并根据按钮的 isActive 属性来动态添加或移除 bg-blue-500 和 text-white 类以实现高亮效果。每个按钮的点击事件调用 toggleButton 方法来切换按钮的 isActive 属性。
请注意,上述示例是一个完整的 HTML 文件,您可以将其保存为 .html 文件并直接在浏览器中打开运行。
原文地址: https://www.cveoy.top/t/topic/qds4 著作权归作者所有。请勿转载和采集!