如何在WordPress Elementor中实现按钮点击时的字体加粗切换?
实现Elementor自定义标签页按钮的加粗选中效果
你只需在现有代码基础上做两处修改,就能实现点击按钮时的文字加粗效果:
1. 完善resetButtonStyles函数
这个函数要负责把所有按钮的字体粗细重置为常规样式,同时保留你原本的背景色重置逻辑。如果之前没定义这个函数,直接补上:
function resetButtonStyles() { // 重置所有按钮的背景色为默认状态 button1.style.backgroundColor = ''; button2.style.backgroundColor = ''; button3.style.backgroundColor = ''; // 重置所有按钮的字体粗细为常规样式 button1.style.fontWeight = 'normal'; button2.style.fontWeight = 'normal'; button3.style.fontWeight = 'normal'; }
2. 在每个按钮的点击事件中添加加粗设置
在每个按钮的点击回调里,把设置当前按钮fontWeight为900的代码,和你设置背景色的代码放在一起即可。
完整的修正后代码如下:
// 先获取页面元素(确保ID和Elementor里设置的一致) const button1 = document.getElementById('button1'); const button2 = document.getElementById('button2'); const button3 = document.getElementById('button3'); const tab1 = document.getElementById('tab1'); // 替换为你实际的标签内容ID const tab2 = document.getElementById('tab2'); const tab3 = document.getElementById('tab3'); // 定义重置样式函数 function resetButtonStyles() { button1.style.backgroundColor = ''; button2.style.backgroundColor = ''; button3.style.backgroundColor = ''; button1.style.fontWeight = 'normal'; button2.style.fontWeight = 'normal'; button3.style.fontWeight = 'normal'; } // 初始化默认选中按钮的样式 button1.style.backgroundColor = 'white'; button1.style.fontWeight = '900'; // 按钮1点击事件 button1.addEventListener('click', function() { tab1.style.display = 'flex'; tab2.style.display = 'none'; tab3.style.display = 'none'; resetButtonStyles(); button1.style.backgroundColor = 'white'; button1.style.fontWeight = '900'; // 添加该行实现加粗 }); // 按钮2点击事件 button2.addEventListener('click', function() { tab1.style.display = 'none'; tab2.style.display = 'flex'; tab3.style.display = 'none'; resetButtonStyles(); button2.style.backgroundColor = 'white'; button2.style.fontWeight = '900'; // 添加该行实现加粗 }); // 按钮3点击事件 button3.addEventListener('click', function() { tab1.style.display = 'none'; tab2.style.display = 'none'; tab3.style.display = 'flex'; resetButtonStyles(); button3.style.backgroundColor = 'white'; button3.style.fontWeight = '900'; // 添加该行实现加粗 });
额外提示
- 如果Elementor默认按钮样式和自定义样式冲突,可以把
fontWeight的值换成bold,或者调整数值(100-900区间内的整数)适配需求。 - 确保标签内容的ID和你Elementor里Text组件设置的ID完全一致,否则会出现切换无效的问题。
内容的提问来源于stack exchange,提问作者Yanna
相关产品推荐
相关产品推荐

