在 JavaScript 中更改文本框的颜色

发布于 2024-09-01 15:26:55 字数 282 浏览 2 评论 0原文

我有这个小的 JavaScript 代码,我需要一些帮助:

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

我在这里需要的是,当有人单击我的文本框时,文本“学生姓名 -”应该更改其颜色,并且应该 text-align = left。我正在寻找诸如 text.color 和 text.align 之类的适当语法。

I have this small JavaScript code which I need some help with:

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. I am looking for the appropriate syntax for something like text.color and text.align.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

紫南 2024-09-08 15:26:55

假设 text 是 DOM 元素,您可能需要尝试以下操作:

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

如果您使用它在文本字段中放置水印,您可能还有兴趣查看以下 Stack Overflow 帖子:

Assuming text is the DOM element, you may want to try the following:

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:

一个人的旅程 2024-09-08 15:26:55

我可能会更改 styleclass 属性以在 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'); 
}

我猜你没有使用 JQuery 或其他框架来展示你的 JS,但以防万一你没有宗教信仰,我还建议使用 JS 框架(如 JQuery)来协助 DOM操纵。

I'd change the style or class attribute to do it in CSS probably.

// 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文