JavaScript如何动态更改CSS页面样式?如果要在JavaScript中更改页面样式,需要更改元素的样式属性,下面我们就来看看具体的实现内容。
我们来直接看示例
代码如下
JavaScriptChangeCssTextBox.html
立即学习“Java免费学习笔记(深入)”;
nbsp;html>function SetColor(foreColor, backColor) { target = document.getElementById("page"); if (target != null) { target.style.backgroundColor = document.form1.Text1.value;; target.style.color = document.form1.Text2.value; } }
登录后复制
说明:
单击表单上的按钮执行用JavaScript编写的SetColor()函数。
function SetColor(foreColor, backColor) { target = document.getElementById("page"); if (target != null) { target.style.backgroundColor = document.form1.Text1.value;; target.style.color = document.form1.Text2.value; }}
登录后复制
在SetColor函数中调用document.getElementById方法,可以从被设定为Body标签的ID中获取Body标签的Element。如果取得了Element(target!= Null),就可以将Element的style属性的background属性和color属性设置为文本框的值。
运行结果
执行HTML文件。将显示如下所示的效果。
在文本框中输入颜色编码,然后点击“button”按钮,就会显示如下所示的效果
输入其他颜色的编码,然后单击button按钮,页面将变为其他颜色
我们下面接着来看下一个示例
代码如下
JavaScriptChangeCssParameter.html
nbsp;html>window.onload = function onLoad() { param = GetQueryString(); target = document.getElementById("page"); if (param != null) { if (param["bgcolor"] != null) { target.style.backgroundColor = "#" + param["bgcolor"]; } if (param["fgcolor"] != null) { target.style.color="#"+ param["fgcolor"]; } } } function GetQueryString() { if (1 < document.location.search.length) { // 获取不包括第一个字符的字符串(?符号) var query = document.location.search.substring(1); // 使用查询分隔符(&)将字符串拆分为数组 var parameters = query.split('&'); var result = new Object(); for (var i = 0; i < parameters.length; i++) { // 拆分为参数名称和参数值 var element = parameters[i].split('='); var paramName = decodeURIComponent(element[0]); var paramValue = decodeURIComponent(element[1]); // 将参数添加到参数作为关联数组,参数名称为键 result[paramName] = decodeURIComponent(paramValue); } return result; } return null; } 这是一个测试页面啦啦啦啦哈哈哈哈
登录后复制
说明:
它类似于以前的HTML文件,但从HTML文件的参数中获取颜色代码并更改前景色和背景色
运行结果:
执行HTML文件,将显示如下所示的效果。
更改网址,通过在URL后面添加“?Bgcolor = C0C0C0”来访问它。将显示如下所示的效果。背景颜色已更改为参数的颜色代码集。
下面是“?bgcolor=202020&fgcolor=00C000”的结果。前景色也改变了。
以上就是本篇文章的全部内容了,更多相关精彩内容的学习可以移步到【创想鸟】的JavaScript视频教程栏目!!!!
以上就是JavaScript如何动态更改CSS页面样式的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2736026.html