用JS实现的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></title>
<style>
.lanrentuku img{border:1px solid #008800;}
</style>
</head>

<body>
<script>
  function myFun(sId) {
    var oImg = document.getElementsByTagName('img');

    for (var i = 0; i < oImg.length; i++) {
      if (oImg[i].id == sId) {
        oImg[i].previousSibling.previousSibling.checked = true;
        oImg[i].style.border = '1px solid #FF6600';
      } else {
        oImg[i].style.border = '1px solid #008800';

      }
    }
  }
</script>
<div class="radio-box">
 <input type="radio" value= "0" id= "eastVeh1" name="eastVeh" style="display:none"> <img id="aa" src="${rootPath}/common/resource/images/P1.png " onclick="myFun(this.id)"> 
 <input type="radio" value= "1" id= "eastVeh2" name="eastVeh" style="display:none"> <img id="bb" src="${rootPath}/common/resource/images/P2.png" onclick="myFun(this.id)"> 
 <input type="radio" value= "2" id= "eastVeh3" name="eastVeh" style="display:none"> <img id="cc" src="${rootPath}/common/resource/images/P3.png" onclick="myFun(this.id)">
</div>
</body>
</html>

效果图:
在这里插入图片描述
鼠标点击选中图片 图片外层会有一个1像素的红线。

这里边比较关键的是 input 标签的 隐藏属性 display:none

如果感觉选中之后 有个红色框框不是很明显的话 可以使用原来的那种单选框的样式 把 style=“display:none” 去掉就行。 然后把img标签中的点击事件调用的方法也删除掉。

<!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></title>
<style>
.lanrentuku img{border:1px solid #008800;}
</style>
</head>

<body>
<div class="radio-box">
 <input type="radio" value= "0" id= "eastVeh1" name="eastVeh" style=""> <img id="aa" src="${rootPath}/common/resource/images/P1.png " onclick=""> 
 <input type="radio" value= "1" id= "eastVeh2" name="eastVeh" style=""> <img id="bb" src="${rootPath}/common/resource/images/P2.png" onclick=""> 
 <input type="radio" value= "2" id= "eastVeh3" name="eastVeh" style=""> <img id="cc" src="${rootPath}/common/resource/images/P3.png" onclick="">
</div>
</body>
</html>

效果图:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

散装程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值