返回jquery获......登陆

jquery获取随机颜色作业和理解

hiki19872018-12-21 14:24:37257
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jquery获取随机颜色</title>
     <script type="text/javascript" src="jquery-3.3.1.min.js"></script>
     <style type="text/css">
     a{
          float: left;
          display: block;
          margin:50px;
          width: 100px;
          line-height: 100px;
          text-align: center;
          height: 100px;
          color: #fff;
          border-radius: 50px;
          text-decoration: none;
     }
     </style>
     <script type="text/javascript">
     //改变标签的背景颜色
     function aa(tag){
          var len=document.getElementsByTagName('a').length
          console.log(len)
          for (var i = 0 ; i<len; i++) {
            document.getElementsByTagName(tag)[i].style.backgroundColor
            ='rgb('+Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256)+')'
               }
          }
     $(document).ready(function(){
          aa('a')
          $('a').mouseover(function(){
               $bg=$(this).css('backgroundColor')
               $(this).css('box-shadow','0px 0px 20px '+$bg)
               $(this).css('border-radius','20px')
          })
          $('a').mouseleave(function(){
          $(this).css('box-shadow','none')
          $(this).css('border-radius','50px')
          })
     })
     </script>
</head>
<body>
     <a href="#">1</a>
     <a href="#">2</a>
     <a href="#">3</a>
     <a href="#">4</a>
</body>
</html>

QQ截图20181221135950.jpg

总结和理解:

刚开被这句话卡主了,

var len=document.getElementsByTagName(tag).length  。因为之前学的都是document.getElementsByTagName( )这里面传的标签。我就把里面改成了

document.getElementsByTagName('a')标签。也可以正常使用。加上console.log(len) 发现2个取出来的都是4,明白了,传入tag指的是所有的标签的个数。

QQ截图20181221141858.jpg

QQ截图20181221141903.jpg

新知识点:

Math.random () 方法获取一个随机值,获取到的是0到-1的值。再使用Math.floor()方法,如果出现小数就进行四舍五入变成整数。

这也是目前我们第1个js和jq配合使用的小案例,受益匪浅。

最新手记推荐

• 用composer安装thinkphp框架的步骤• 省市区接口说明• 用thinkphp,后台新增栏目• 管理员添加编辑删除• 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消回复发送