如何用css控制input中的text和radio


在制作表单页面的时候,如果页面有很多表单,我就不愿意单独定义一个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的办法来解决这个问题

示例显示:


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3