我们来直接看示例
代码如下
JavaScriptChangeCssTextBox.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
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;
}
}
</script>
</head>
<body id="page">
<form name="form1">
<div>背景色<input id="Text1" type="text" /></div>
<div>前景色<input id="Text2" type="text" /></div>
<input id="Button1" type="button" value="button" onclick="SetColor()"/>
</form>
</body>
</html>说明:
单击表单上的按钮执行用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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
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;
}
</script>
</head>
<body id="page">
<div>这是一个测试页面</div>
<div>啦啦啦啦</div>
<div>哈哈哈哈</div>
</body>
</html>说明:
它类似于以前的HTML文件,但从HTML文件的参数中获取颜色代码并更改前景色和背景色
运行结果:
执行HTML文件,将显示如下所示的效果。
更改网址,通过在URL后面添加“?Bgcolor = C0C0C0”来访问它。将显示如下所示的效果。背景颜色已更改为参数的颜色代码集。
下面是“?bgcolor=202020&fgcolor=00C000”的结果。前景色也改变了。
Copyright © 2019- huatuo0.cn 版权所有 湘ICP备2023017654号-2
违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务