日期:2014-05-16  浏览次数:20370 次

js 动态改变样式例子

请看代码:

?

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

    <title>用JS动态改变样式</title>
    
<script language="javascript" type="text/javascript">

function $(element) {
	  if (typeof element == 'string')
	    return document.getElementById(element);
}

//获取焦点时触发
function questionOnFocus(obj){
	
	if (obj.value =='请输入您的问题!(限40字)'){
		$("ptitle").className = "my_font_color2";
		obj.value ='';
	}
}

//失去焦点时触发
function questionOnBlur(obj){

	if(obj.value =='' || obj.value =='请输入您的问题!(限40字)'){
		$("ptitle").className= "my_font_color1";
	}
	else{
		$("ptitle").className = "my_font_color2";
    }

    if(obj.value ==''){
		obj.value='请输入您的问题!(限40字)';
	}
}

//获取焦点时触发
function descriptionOnFocus(obj){

	
	if (obj.value =='请描述您的问题!(限500字)'){
		$("pcontent").className = "my_font_color2";
		obj.value ='';
	}
}

//失去焦点时触发
function descriptiOnBlur(obj){

	if (obj.value ==''){
		$("pcontent").className= "my_font_color1";
		obj.value='请描述您的问题!(限500字)';
	}
	else{
		$("pcontent").className = "my_font_color2";
    }
}
</script>

<style>

.my_font_color1{font-family:Arial, Helvetica, sans-serif;color:blue;}
.my_font_color2{font-family:Arial, Helvetica, sans-serif;color:red;}

</style>    

  </head>
  
  <body>
    <center>
			标题:<input type="text" size="34" maxlength="40"
								id="ptitle" name="ptitle"
								value="请输入您的问题!(限40字)" 
								class="my_font_color1"
								onBlur="questionOnBlur(this)"
								onFocus="questionOnFocus(this)"></input>
			<br/>描述:
			<textarea id="pcontent" name="pcontent" 
								cols="37" rows="7"
								onBlur="descriptiOnBlur(this)"
								onFocus="descriptionOnFocus(this)"
								class="my_font_color1">请描述您的问题!(限500字)</textarea>
		</center>
  </body>
</html>
?

上面就是简单的js改变样式的例子。

?