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

如何在ASP.NET中添加交换两个文本框值的按钮及后端代码?

ASP.NET实现两个TextBox值互换(带切换样式按钮)

下面是完整的实现方案,包含ASP.NET服务器控件、自定义切换按钮样式和前端互换逻辑:

1. ASP.NET页面HTML结构

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SwapTextBox.aspx.cs" Inherits="YourNamespace.SwapTextBox" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>TextBox值互换</title>
    <link rel="stylesheet" type="text/css" href="SwapStyle.css" />
</head>
<body>
    <form id="form1" runat="server">
        <div class="swap-container">
            <asp:TextBox ID="txtLeft" runat="server" ClientIDMode="Static" CssClass="swap-input" placeholder="左侧输入框"></asp:TextBox>
            <button type="button" id="btnSwap" class="swap-btn">
                <span class="swap-icon">↔</span>
            </button>
            <asp:TextBox ID="txtRight" runat="server" ClientIDMode="Static" CssClass="swap-input" placeholder="右侧输入框"></asp:TextBox>
        </div>

        <script type="text/javascript">
            document.getElementById('btnSwap').addEventListener('click', function() {
                // 获取两个输入框元素
                const leftInput = document.getElementById('txtLeft');
                const rightInput = document.getElementById('txtRight');
                
                // 临时存储值,完成互换
                const tempValue = leftInput.value;
                leftInput.value = rightInput.value;
                rightInput.value = tempValue;
                
                // 点击反馈动画
                this.classList.add('btn-active');
                setTimeout(() => this.classList.remove('btn-active'), 200);
            });
        </script>
    </form>
</body>
</html>

2. CSS样式(SwapStyle.css)

.swap-container {
    display: flex;
    align-items: center;
    gap: 12px;
    margin: 20px;
}

.swap-input {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    width: 200px;
    font-size: 14px;
}

.swap-btn {
    width: 40px;
    height: 40px;
    border: none;
    border-radius: 50%;
    background-color: #007bff;
    color: white;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    transition: all 0.2s ease;
}

.swap-btn:hover {
    background-color: #0056b3;
    transform: rotate(180deg);
}

.swap-btn.btn-active {
    transform: scale(0.95) rotate(180deg);
    background-color: #004085;
}

.swap-icon {
    pointer-events: none;
}

关键说明

  • 用ClientIDMode="Static"确保ASP.NET服务器控件渲染后的ID和后台定义一致,避免前端JS找不到元素
  • 按钮样式模拟了toggle切换的交互效果:hover时旋转180度,点击时有缩放反馈,贴合你要的swap toggle风格
  • 互换逻辑核心是用临时变量存储其中一个输入框的值,完成双向赋值,实现即时UI效果
  • 如果需要后台同步处理互换后的值,可把按钮改成<asp:Button>并添加后台点击事件,前端互换后提交表单即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 09:00:58