效果图
点击“+”画出的内容变宽
点击“-”画出的内容变细
点击“改变颜色”,颜色随机改变
左下角显示鼠标按下时的坐标
HTML
<input type="button" name="" id="btn1" value="+" />
<input type="button" name="" id="btn2" value="-" />
<input type="button" name="" id="color" value="点击改变颜色" />
<span id="xy"></span>
CSS
<style type="text/css">
#xy {
position: fixed;
left: 0;
bottom: 0;
}
.box {
border-radius: 50%;
position: absolute;
}
input {
position: absolute;
z-index: 999999999999;
}
input:nth-child(2) {
left: 50px;
}
input:nth-child(3) {
left: 100px;
}
</style>
JS
//获取鼠标坐标所在的元素
var xy = document.getElementById('xy');
//获取“+”号元素
var add = document.getElementById('btn1');
//获取“-”号元素
var sub = document.getElementById('btn2');
//获取颜色按钮
var colorBtn=document.querySelector('#color');
//设置初始宽高
var w=5,h=5;
//设置初始颜色
var color='aqua'
//在网页中鼠标按下时
document.onmousedown = function () {
//鼠标移动事件
document.onmousemove = function (eve) {
var e = window.event || eve;
//左下角鼠标的坐标添加到页面中
xy.innerHTML = "x:" + e.clientX + "px, y:" + e.clientY + "px";
//创建一个div元素
var div = document.createElement("div");
//设置元素的样式
div.style.width = w + 'px';//宽
div.style.height = h + 'px';//高
div.style.backgroundColor = color;//背景色
//元素要随着鼠标移动,所以设置元素为绝对定位,脱离文档流
div.style.position = 'absolute';
div.style.left = e.clientX + 'px';//元素距左边的位置为鼠标距左边即x轴坐标的距离
div.style.top = e.clientY + 'px';//元素距上边的位置为鼠标距上边即y轴坐标的距离
div.style.borderRadius = '50%';//设置div为圆形
document.body.appendChild(div)//将div追加到页面中
}
}
//鼠标停止按下时
document.onmouseup = function () {
//鼠标移动事件结束
document.onmousemove = null;
}
//点击“+”号时div变大
add.onclick = function () {
w+=2;
h+=2;
}
//点击“-”号时div变小
sub.onclick=function(){
w-=2;
h-=2;
}
//点击颜色按钮时变色
colorBtn.onclick=function(){
var colorRandom='#'
var c=['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'];
for(var i=0;i<6;i++){
var j=parseInt(Math.random()*16);
colorRandom+=c[j]
}
color=colorRandom;
}