You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PyScript修改页面元素?按钮变色代码故障求助

PyScript按钮点击变色功能修复方案

问题排查

你的代码存在两处关键问题导致功能失效:

  • 事件绑定语法错误:按钮的py-click属性写了colorChange(),带括号会在页面加载时立即执行函数,而非点击按钮时触发。PyScript绑定事件处理器只需写函数名。
  • 样式修改方式不当:使用setAttribute("style")会完全覆盖元素原有style属性,推荐直接操作元素的style对象属性来修改样式,更灵活且不会丢失其他样式。

修复后的完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://pyscript.net/releases/2023.11.1/core.css" />
    <script type="module" src="https://pyscript.net/releases/2023.11.1/core.js"></script>
</head>
<body>
    <div>
        <!-- 移除函数调用的括号 -->
        <button id="run" py-click="colorChange">CLICK</button>
    </div>
    <style>
        #run{ background-color: rgb(61, 139, 130)}
    </style>
    <py-script>
        from js import document
        runButton = document.getElementById("run")
        
        def colorChange(event):
            # 直接修改style对象的backgroundColor属性
            runButton.style.backgroundColor = "red"
    </py-script>
</body>
</html>

额外优化建议

如果需要实现点击切换颜色(初始色与红色交替),可以调整函数逻辑:

def colorChange(event):
    current_color = runButton.style.backgroundColor
    # 注意:通过style获取的颜色值会转为rgb格式字符串,初始未修改时为空
    if current_color == "rgb(61, 139, 130)" or current_color == "":
        runButton.style.backgroundColor = "red"
    else:
        runButton.style.backgroundColor = "rgb(61, 139, 130)"

内容的提问来源于stack exchange,提问作者Joselu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 09:52:27