学习js都会学习到这几个经典的小实例,我抽了三个实例,再来回顾一下吧!
实例一:
获取鼠标在页面可视区域的位置坐标使用哪个属性?获取鼠标相对于页面的绝对坐标(包含页面滚动的距离)如何计算?获取鼠标相对于某个元素的位置使用什么属性?
document.addEventListener('mousemove', function(event) {
// 获取鼠标在页面可视区域的位置坐标
const x = event.clientX;
const y = event.clientY;
console.log('鼠标在页面可视区域的位置坐标:(x=' + x + ', y=' + y + ')');
// 获取鼠标相对于页面的绝对坐标(包含页面滚动的距离)
const absX = event.pageX;
const absY = event.pageY;
console.log('鼠标相对于页面的绝对坐标:(x=' + absX + ', y=' + absY + ')');
// 获取鼠标相对于某个元素的位置
const target = event.target;
const offsetX = event.offsetX;
const offsetY = event.offsetY;
console.log('鼠标相对于元素 ' + target.tagName + ' 的位置:(x=' + offsetX + ', y=' + offsetY + ')');
});
实例二:
应用JavaScript编程实现打印任意奇数行菱形
var row=Number(prompt('请输入打印(奇数)行:'));
var s=Math.floor(row/2)+1;
for(var i=1;i<=row;i++){
for(var k=1;k<=Math.abs(s-i);k++){
document.write('--');
}
for(var j=1;j<=2*s-1-2*Math.abs(s-i);j++){
document.write('*');
}
document.write('</br>');
}
实例三:
封装函数,功能获取一个随机颜色值
function rgb(){
const r=Math.floor(Math.random()*256);
const g=Math.floor(Math.random()*256);
const b=Math.floor(Math.random()*256);
return `rgb(${r},${g},${b})`;
}