简体   繁体   English

如何通过Javascript更改文本框的背景颜色?

[英]How to change background color of TextBox by Javascript?

I am trying to change background color of textbox by using javascript but my code is not working. 我正在尝试使用javascript更改文本框的背景颜色,但是我的代码无法正常工作。 I search SO but not find any suitable answer. 我这样搜索,但找不到任何合适的答案。 Here is my code. 这是我的代码。

<head>
    <script type="text/javascript" language="javascript">
        function abc() {
            var v = document.getElementById("<%=TextBox1.ClientID%>");
            v.setAttribute('BackColor', 'Red');
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="abc()" onclick="Button1_Click"/>
    </div>
    </form>
</body>

在此处输入图片说明

You are trying to change the UI that is html, so you need to use javascript/css properties. 您正在尝试更改html的UI,因此需要使用javascript / css属性。

Here there is a list of css attributes accessible by javascript. 这里是可通过javascript访问的CSS属性的列表。

Try with: 尝试:

   <script type="text/javascript" language="javascript">
        function abc() {
            var v = document.getElementById("<%=TextBox1.ClientID%>");
            v.style.backgroundColor = "red";
        }
    </script>

Furthermore I have the Visual Studio 2010 and the Intellisense also show me the style attribute: 此外,我有Visual Studio 2010,Intellisense也向我展示了style属性:

在此处输入图片说明

You are right jams, when I pretend to point to an id from a html generated by asp the intellisense doesn't works for the style attribute: 您是对的,当我假装指向由asp生成的html中的id ,intellisense不适用于style属性:

在此处输入图片说明

在此处输入图片说明

I think the Intellisense doesn't reach to this id because at the moment of you are writting this code, the html doesn't exists. 我认为Intellisense无法到达此id因为在您编写此代码时,html不存在。

BackColor does not exist on the client side. 客户端上不存在BackColor That's an ASP.NET server-side notion. 这就是ASP.NET服务器端的概念。 Rather, you want to set it with CSS: 相反,您想使用CSS进行设置:

v.style.backgroundColor = 'Red';

Here is a reference of the names of CSS properties as they would appear in JavaScript. 是CSS属性名称的引用,就像它们在JavaScript中一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM