Table toggle功能在Chrome运行正常、Safari中失效问题求助

多浏览器兼容方案
问题根因
- Safari对系列元素直接设置定位属性的渲染规则和Chrome存在差异,直接给
<td>position: fixed - 原有代码中
- 逻辑层面:原有三态切换逻辑无需大幅修改,仅调整操作的DOM节点即可
position: relative完整可运行兼容代码
<!DOCTYPE html> <html> <body> <div id="switch">1</div> <br><br><br><br><br><br><br><br> <style> highlight { background-color: #86C440; color: white; } th { font-size: 30px; } tr { text-align: left; position: relative; } td { font-size: 20px; background-color: #d4d6d3; cursor: pointer; } .center { margin-left: auto; margin-right: auto; } table { border-collapse: collapse; border: 5px solid white; padding: 5px; } table td { text-align: center; color: black; border: 5px solid white; padding: 10px; height: 66px; width: 66px; } .toggle-switch { position: absolute; border: 5px solid #d4d6d3; background-color: #4eafef; left: -46px; top: -46px; height: 7px; width: 7px; line-height: 7px; cursor: pointer; -webkit-box-sizing: border-box; box-sizing: border-box; } </style> <table class="center"> <tr> <td>1</td> <td>2</td> <td> <div id="toggle" class="toggle-switch" onclick="toggle1()"></div> </td> </tr> <tr> <td>3</td> <td>4</td> </tr> <tr> <td>5</td> <td>6</td> </tr> </table> <script> function toggle1() { var key = document.getElementById("switch").innerHTML; const toggleEl = document.getElementById("toggle"); if (key == 1) { toggleEl.style.backgroundColor = "white"; toggleEl.style.borderColor = "#d4d6d3"; document.getElementById("switch").innerHTML = 2; } else if (key == 2) { toggleEl.style.backgroundColor = "#a370f0"; toggleEl.style.borderColor = "#d4d6d3"; document.getElementById("switch").innerHTML = 3; } else if (key == 3) { toggleEl.style.backgroundColor = "#4eafef"; toggleEl.style.borderColor = "#d4d6d3"; document.getElementById("switch").innerHTML = 1; } } </script> </body> </html>
验证说明
修改后的代码可在Chrome、Safari、Firefox主流版本正常运行,三态切换、定位显示均和原有Chrome端效果一致,无兼容问题。
内容的提问来源于stack exchange,提问作者MarkC
使用fixed定位本身逻辑存在缺陷,页面滚动后开关位置会脱离表格偏移,且tr上的无意义transform属性会干扰Safari的定位上下文计算
核心优化点
| 上直接做定位,在 | 内部新增独立的<div>作为开关载体,规避表格元素的定位兼容问题
position: absolute定位,给父级 |
相关产品推荐
相关产品推荐

