练习:点击按钮图片位置随机和随机颜色

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box1{
            height: 100px;
            width: 200px;
            background: #bfa;
            border: 2px solid red;
        }
    </style>
</head>
<body>


    <!-- <div id="box1"></div> -->
    <!-- <input type="button" value="新增元素" onclick="addElement()"> -->
    <input type="button" id="btn_1" value="新增元素">
    获取焦点事件:<input type="text" id="input_1">

</body>
<script>
    //实现在js代码中绑定事件
//1、获取事件源对象,按钮
    var button=document.querySelector("#btn_1");
    var input_1=document.querySelector("#input_1");

//2、绑定事件
    button.onclick=function(){
        // alert("绑定成功");
        addElement();
        changeColor();
    //     var bgColor="";
	// 	for(var i=0; i<6; i++){
	// 		bgColor += '' + Math.round(Math.random()*9);
    //     }
    //     document.body.style.backgroundColor='#'+bgColor;
    }
    // button.onclick=false;

    //  **在随机生成图片的基础上,加上随机改变页面的背景色
        function changeColor(){
            var body=document.body;
            var R=Math.random()*255;
            var G=Math.random()*255;
            var B=Math.random()*255;
            body.style.backgroundColor="rgb("+R+","+G+","+B+")";
                
        }

//3、addEventlistener
    //添加事件监听器
    // button.addEventListener("click",addElement);
    // button.addEventListener("click",changeColo);
    // button.addEventListener("click",function(){
    //     alert("绑定成功");
    // })
    // button.removeEventListener("click",addElement);
    // button.addEventListener("click",test);



/* d对比绑定事件的三种方式
    1.行内绑定
        写在哪个标签就是给哪个标签绑定事件
        无法通过代码实现给多个元素同时绑定事件
    2.元素.onclick()
        同一个元素相同的时间只能绑定一次,以后绑定的事件为准
    3.元素.addEventListerner()
        同一个元素可以添加多个事件监听器,都会执行,后添加的监听器先执行
*/

    function addElement(){
        //实现向页面添加元素
        var box=document.createElement("img");
        box.style.width="100px";
        box.style.height="100px";
        box.style.backgroundColor="#bfa";
        box.style.position="absolute";
        box.style.left=Math.random()*800+"px";
        box.style.top=Math.random()*200+"px";
        box.src="1.jpg";
        var body=document.body;
        body.appendChild(box);
    }





    // var box=document.querySelector("#box1");
    // alert(box.getAttribute("id"));
    // box.setAttribute("class","box");
    // //如何修改页面元素样式
    // box.style.border="0px solid red";
    // box.className="boxType";
</script>
</html>

实现效果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值