JavaScipt30(第二十二个案例)(主要知识点:getBoundingClientRect)
2024-08-30 12:15:38
这是第二十二个案例,这个例子实现的是鼠标移入a标签时,将其高亮。
附上项目链接: https://github.com/wesbos/JavaScript30
以下为注释后的源码:
<script>
const triggers = document.querySelectorAll('a');
const highlight = document.createElement('span');
highlight.classList.add('highlight');
document.body.appendChild(highlight); function highlightLink() {
// 返回值是一个DOMRect对象,DOMRect 对象包含了一组用于描述边框的只读属性——left、top、right和bottom,单位为像素。
const linkCoords = this.getBoundingClientRect();
const coords = {
width: linkCoords.width,
height: linkCoords.height,
// 这里有个值得注意的点是,因为DOMRect是相对于视口的左上角位置而言的,所以需要加上滚动的scrollY或scrollX
top: linkCoords.top + window.scrollY,
left: linkCoords.left + window.scrollX
}; highlight.style.width = `${coords.width}px`;
highlight.style.height = `${coords.height}px`;
// 除了定位外的另一种移到某个位置的方法,要记得用
highlight.style.transform = `translate(${coords.left}px, ${coords.top}px)`;
} triggers.forEach(a => a.addEventListener('mouseenter', highlightLink));
</script>
最新文章
- egret3D与2D混合开发,画布尺寸不一致的问题
- oracle10g冷备份和恢复过程记录
- UVa 1328 Period
- oracle强化练习之分组函数
- AS3.0的int uint Number的使用原则
- android中listview的一些样式设置
- SPJ 讨论
- Linux 下搭建jsp服务器(配置jsp开发环境)
- LogFactory缺包异常
- shell初步了解
- 探讨.NET Core数据加密和解密问题
- jquery按钮倒计时
- fmod函数和modf函数
- mybatis-generator 根据表生成对应文件
- ListView 无 DataSource 依然用 DataPager 翻页
- 微信小程序开发库grace vs wepy
- PHP常用方法整理
- git心得与总结
- 用socket写一个简单的客户端和服务端程序
- 【Redis】编译错误zmalloc.h:50:31: fatal error: jemalloc/jemalloc.h: No such file or directory