获取页面元素、随机色、Math对象

获取页面元素

获取元素的四种方式:
1. 通过标签名来获取
2. 通过class类名 来获取
3. 通过id名来获取
4. 通过name属性来获取

<div>我是通过标签名获取的</div>
<div class="div1">我是通过class类名获取的</div>
<div id="div2">
		我是通过id名来获取的
		<span>ssss</span>
</div>
<div name="div3">我是通过name来获取的
		<span>ssss</span>
</div>
< script>
       var box = document.getElementsByTagName("div")[2];
       console.log(box);

       var box2 = document.getElementsByClassName("div1")[0];
       console.log(box2);

       var box3 = document.getElementById("div2");
       console.log(box3);

       var box4 = document.getElementsByName("div3")[0];
       console.log(box4);
< /script>

设置HTML标签的文字
innerHTML: 会修改开始标签到结束标签之间,所有的内容(覆盖子元素)
innerText: 只会修改文本内容

< script>
       box4.innerHTML = "我被js给修改了";
       box3.innerText = "我也被js给修改了";

//通过js 来修改html 的样式
       box.style.width = 100 + "px";
       box.style.height = 100 + "px";
       box.style.backgroundColor = "red";
......
< /script>

随机色

颜色的赋值:
1. 通过英文名称
2. 通过rgb三原色调配比例,来赋值
3. 通过16进制位数,来匹配对应的颜色

< style>
       .box{
					width: 100px;
					height: 100px;
					background-color: rgb(140,230,120);
				}
< /style>

opacity 透明度
取值范围 0~1
1 为不透明, 0为完全透明

< style>
       .box{
					width: 100px;
					height: 100px;
					background: red;
					opacity: 0.5;
				}
< /style>

rgba(): 4个参数 r g b a ,必须要四个参数,一个都不能少
a : 透明度

< style>
       .box{
					width: 100px;
					height: 100px;
					background-color: rgba(200,100,10,0.6);
				}
< /style>

在js中

<script type="text/javascript">		
			var box = document.getElementsByClassName("box")[0];		
			function c(){
				return  Math.floor(Math.random()*255);
			}	
			//通过使用 rgb三原色 来完成随机颜色的赋值
			box.style.backgroundColor = 'rgb(' + c() + ',' + c() + ','+ c()+ ')';			
	</script>

Math对象

Math对象: 是js提供给开发者的一款内置常见数学公式的对象,所有Math对象中的方法, 都会有返回值。
定义一个随机数:Math.random()*(较大的数 - 较小的数) + 较小的数
去掉随机数中 的小数
Math.ceil() : 向上取整
Math.floor() : 向下取整
Math.round() : 四舍五入

1.范围只确定终点 的随机数 
			var one = Math.random()*10;
			console.log(one);
2.范围两端都确定的 随机数
			var two = Math.random()*(10-7)+7;
			console.log(two);				 
3. 去掉随机数中 的小数
            var three = Math.ceil(Math.random()*(100 - 50)+ 50);	
			console.log(three);

练习: 1.输出10个50~100之间的随机数,并求出他们之间的和

 < script>  
            var sum = 0;
			var num = 0;
			
			for(i=0;i<10;i++){
				sum = Math.ceil(Math.random()*(100-50)+50);
				document.write("随机数的和为:"+ sum);
				num += sum;
			}
			    document.write(num);		
< /script>
发布了42 篇原创文章 · 获赞 0 · 访问量 878

猜你喜欢

转载自blog.csdn.net/cybcc/article/details/104132690
今日推荐