简体   繁体   English

在JavaScript中更改文本框的颜色

[英]Change color of textbox in JavaScript

I have this small JavaScript code which I need some help with: 我有这个小的JavaScript代码,需要以下帮助:

function doFocus(text) {
    if (text.value == "Enter Name") {
       text.value = "Student Name -";
    }
}

All I need here is when someone clicks on my textbox, the text "Student Name -" should change its color, and should text-align = left. 我需要做的是,当有人单击我的文本框时,文本“学生姓名-”应更改其颜色,并且text-align = left。 I am looking for the appropriate syntax for something like text.color and text.align. 我正在寻找诸如text.color和text.align之类的适当语法。

Assuming text is the DOM element, you may want to try the following: 假设text是DOM元素,则可能需要尝试以下操作:

function doFocus(text) {
   if (text.value === 'Enter Name') {
       text.value = 'Student Name -';
       text.style.color = 'red';
       text.style.textAlign = 'left';
   }
}

If you are using this to place a watermark in your text field, you may also be interested in checking out the following Stack Overflow post: 如果您正在使用它在文本字段中放置水印,那么您可能也有兴趣查看以下Stack Overflow帖子:

I'd change the style or class attribute to do it in CSS probably. 我可能会更改样式属性以在CSS中完成。

// JS pseudocode just to get the idea across
var textBox = getTheTextBox();
if (textBox.value == "bla")
{
    // use JS framework like JQuery to change the css class
    textBox.class('highlight'); 
}

I'm guessing for the example you didn't show your JS using JQuery or some other framework, but just in case you haven't got the religion, I'd also suggest using a JS framework such as JQuery to assist in the DOM manipulation. 我在猜测您没有使用JQuery或其他框架来显示JS的示例,但是为了以防万一,您还建议使用JQuery这样的JS框架来协助DOM。操纵。

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

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