我有13个按钮对齐,当用户选择一个,它必须改变其背景颜色,并保持不变,当用户从点击事件显示的表单返回,所以必须为相同的.我测试了很多方法都没有成功,我需要帮助,请
kt06eoxx1#
如果我正确理解了你的问题,当一个按钮被点击时,你希望一个按钮在点击时改变颜色?如果是这样,这个答案可以通过html和一些JavaScript找到:您可以使用JavaScript来处理按钮点击并管理所选按钮的状态。您可以将所选按钮存储在浏览器的localStorage中,以便即使用户导航离开并返回,也可以保留其状态。函数的作用是:在按钮上切换“selected”类,并更新localStorage。当页面加载时,它会检查localStorage来设置按钮的初始状态。即使用户离开并返回页面,选定的按钮也会保持其状态。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .button { padding: 10px; margin: 5px; cursor: pointer; } .selected { background-color: lightblue; /* Change this to your desired background color */ } </style> </head> <body> <button class="button" id="button1">Button 1</button> <button class="button" id="button2">Button 2</button> <button class="button" id="button3">Button 3</button> <button class="button" id="button4">Button 4</button> <button class="button" id="button5">Button 5</button> <button class="button" id="button6">Button 6</button> <button class="button" id="button7">Button 7</button> <button class="button" id="button8">Button 8</button> <button class="button" id="button9">Button 9</button> <button class="button" id="button10">Button 10</button> <button class="button" id="button11">Button 11</button> <button class="button" id="button12">Button 12</button> <button class="button" id="button13">Button 13</button> <script> // Simple object to mimic localStorage const mockLocalStorage = {}; // Function to handle button clicks function handleButtonClick(buttonId) { const button = document.getElementById(buttonId); // Toggle the background color if (button.classList.contains('selected')) { button.classList.remove('selected'); // Remove from mockLocalStorage when deselected delete mockLocalStorage[buttonId]; } else { button.classList.add('selected'); // Save to mockLocalStorage when selected mockLocalStorage[buttonId] = 'selected'; } } // Function to set initial button states function setInitialButtonStates() { const buttons = document.querySelectorAll('.button'); buttons.forEach(button => { // Check mockLocalStorage to set the initial state if (mockLocalStorage[button.id] === 'selected') { button.classList.add('selected'); } }); } // Add click event listeners to the buttons const buttons = document.querySelectorAll('.button'); buttons.forEach(button => { button.addEventListener('click', () => { handleButtonClick(button.id); }); }); // Set initial button states when the page loads setInitialButtonStates(); </script> </body> </html>
字符串
1条答案
按热度按时间kt06eoxx1#
如果我正确理解了你的问题,当一个按钮被点击时,你希望一个按钮在点击时改变颜色?如果是这样,这个答案可以通过html和一些JavaScript找到:您可以使用JavaScript来处理按钮点击并管理所选按钮的状态。您可以将所选按钮存储在浏览器的localStorage中,以便即使用户导航离开并返回,也可以保留其状态。函数的作用是:在按钮上切换“selected”类,并更新localStorage。当页面加载时,它会检查localStorage来设置按钮的初始状态。即使用户离开并返回页面,选定的按钮也会保持其状态。
字符串