您的位置:首页 > Web前端 > CSS

css 控制 input 的text 和radio

2012-03-26 16:38 363 查看
在制作表单页面的时候,如果页面有很多表单,我就不愿意单独定义一个input样式 然后每个input text下都去调用这个css(<input type="text" name="textfield" class="" />).我觉得这样每个input引用css的做法不理想,而且也太麻烦了.我习惯定义一个总的input样式。如input { border:1px solid #f00} ,这样为所有的input定义了一个红色边框。这样就必须在radio调用一个无红色边框的css 如:.radio { border:none}
把radio的红色边框去掉.但这样radio的外观就和默认情况下的相比不美观了很多。我在做网站的时候就碰到这样的问题,如图:

没有定义input,默认的情况下:



定义了input全局样式的情况下 radio的外观就难看了许多:



那如何用css控制input中的text和radio呢?网页设计找到了两个解决办法,还是以示例来说明:

方法一:



<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=gb2312" />

<title>css如何控制input中的text和radio</title>

<style type="text/css">

<!--

input{behavior:url(text.htc)}

-->

</style>

</head>

<body>

<input type="text" name="textfield" />

<input type="radio" name="radiobutton" value="radiobutton" />

</body>

</html>

就是在css中调用了text.htc文件。何谓htc文件?htc的全称就是html components,由微软在ie5.0后开始提供的一种新的指令组合,它是一个javascript的代码文件,主要把javascript代码封装起来。所以htc文件只在ie下有效。

在text.htc文件中写入代码:

<public:component>

<public:attach event="oncontentready" onevent="init()" />

<public:attach event="ondetach" onevent="on_deatch()" />

<script>

function init()

{

if(element.type=="text")

{

element.style.border="1px solid #f00"

}

}

</script>

</public:component>

ps:此方法的一个bug是在firefox下不支持。而且据说用htc比较占资源。所以不推荐使用。

方法二:

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="content-type" content="text/html; charset=gb2312" />

<title>css如何控制input中的text和radio</title>

</head>

<body>

<input type="text" name="textfield" />

<input type="radio" name="radiobutton" value="radiobutton" />

</body>

</html>

<script language="javascript" type="text/javascript">

var obj = document.getelementsbytagname("input");

for (var i=0; i<obj.length; i++)

{

if (obj[i].type=="text"){obj[i].style.border="1px solid #f00" }

}

</script>

ps:就是在页面最下面加上这端js代码。这个方法比较实用,也可以推荐使用,特别感谢可乐用js的办法来解决这个问题

示例显示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: