javascript动态设置样式style实例分析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

javascript动态设置样式style实例分析

永远爱好写程序   2020-05-13 我要评论

本文实例讲述了javascript动态设置样式style的方法。分享给大家供大家参考。具体分析如下:

动态修改style

1.易错:修改元素的样式不是设置class属性,而是className属性.
2.易错:单独修改样式的属性使用"style.属性名".注意在css中属性名在javascript中

操作的时候属性名可能不一样,主要集中在那些属性名中含有-的属性,因为

javascript中-是不能做属性,类名的。所以在CSS中背景色是background-clolor,而javascript中则是style.background;元素样式名是class,在javascript中是className属性;font-size->style.fontSize;margin-top->style.marginTop

3.单独修改控件的样式<input type="button" value="AAA" onclick="this.style.color='red'" />

1.举例1

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title>动态修改style</title>
 <style type="text/css">
 .day
 {
 background-color:Green;
 }
 .night
 {
 background-color:Black;
 }
 </style>
 <script type="text/javascript">
 function dayclick() {
 var divMain = document.getElementById("divMain");
 //注意这里使用的是className而不是class
 divMain.className = "day";
 }
 function nightclick() {
 var divMain = document.getElementById("divMain");
 divMain.className = "night";
 }
 </script>
</head>
<body>
 <div id="divMain" class="day">
 <font color="red">中华人名共和国</font>
 </div>
 <input type="button" value="白天" onclick="dayclick()" />
 <input type="button" value="黑夜" onclick="nightclick()" />
</body>
</html>

2. 示例:动态修改style(模拟开灯,关灯)

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title></title>
 <style type="text/css">
 .day
 {
 background-color:White;
 }
 .night
 {
 background-color:Black;
 }
 </style>
 <script type="text/javascript">
 function switchLight() {
 var btnSwitch = document.getElementById("btnSwitch");
 if (document.body.className == "day") {
 document.body.className = "night";
 btnSwitch.value = "开灯";
 }
 else {
 document.body.className = "day";
 btnSwitch.value = "关灯"; 
 }
 }
 </script>
</head>
<body class="night">
<input type="button" value="开灯" id="btnSwitch" onclick="switchLight()"/>
</body>
</html>

3. 示例:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title>动态设置style练习(修改文本框背景色)</title>
 <script type="text/javascript">
 function IniEvents() {
 var inputs = document.getElementsByTagName("input");
 for (var i = 0; i < inputs.length; i++) {
 if (inputs[i].type == "text") {
  //设置txtOnBlur函数为input元素的onblur事件的响应函数
  inputs[i].onblur = txtOnBlur;
 }
 }
 }
 function txtOnBlur() {
 /*
 txtOnBlur是onblur的响应函数,而不是被响应函数调用
 的函数,所有可以用this来取的发生事件控件的对象
 */
 if (this.value.length <= 0) {
 this.style.background = "red";
 }
 else {
 this.style.background = "white";
 }
 }
 </script>
</head>
<body onload="IniEvents()">
 <input type="text" /><br />
 <input type="text" /><br />
 <input type="text" /><br />
 <input type="text" /><br />
 <input type="text" /><br />
 <input type="text" /><br />
</body>
</html>

希望本文所述对大家的javascript程序设计有所帮助。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们