使用if语句HTML分配Class

时间:2013-10-21 14:44:56

标签: css html5 onblur onfocus

我正在制作一个外观漂亮的登录系统,所以我想在表单中输入内容时更改文本的颜色,但是我无法弄清楚如何,我为他们分配了一个类以使其工作但它不会似乎工作。

HTML: -

    <div class="Login">
                <form name="form1" method="get" action="index.php">
                <input type="text" value="Username" name="Username" onblur="if (this.value === '') {this.value = 'Username'; this.class='Offline';}" onfocus="if (this.value === 'Username') {this.value = ''; this.class='Online';}">
                <input type="text" value="Password" name="Password" onblur="if (this.value === '') {this.value = 'Password';}" onfocus="if (this.value === 'Password') {this.value = '';}">
                <input type= "Submit" Name= "Submit" value= "Login" class="Button">
                </form>
    </div>

并且我在这些类中更改CSS中的颜色。但它似乎工作,任何人都可以在这里指导我,我没有很多javascript的脚本经验,所以我不想去那边

4 个答案:

答案 0 :(得分:0)

使用this.className代替this.class

 <input type="text" value="Username" name="Username" onblur="if (this.value === '') {this.value = 'Username'; this.className='Offline';}" onfocus="if (this.value === 'Username') {this.value = ''; this.className='Online';}">

JsFiddle Demo

答案 1 :(得分:0)

使用this.className代替this.class

<input type="text" value="Username" name="Username" onblur="if (this.value === '') {this.value = 'Username'; this.className='Offline'}" onfocus="if (this.value === 'Username') {this.value = ''; this.className='Online';}">

Example

<强>更新

您必须更改条件,因为条件不满意并且未应用类:

<input type="text" value="Username" name="Username" onblur="if (this.value != '') <-- Here {this.value = 'Username'; this.className='Offline'}" onfocus="if (this.value === 'Username') {this.value = ''; this.className='Online';}">

Updated Fiddle

答案 2 :(得分:0)

你试过Jquery吗?

$(this).attr('class','yourclass');

$(this).removeClass('Offline');
$(this).addClass('Online');

答案 3 :(得分:0)

您应该使用setAttribute和getAttribute方法而不是class或className属性。

相关问题