JS-点击效果
发布日期:2021-05-12 03:06:58 浏览次数:24 分类:精选文章

本文共 1035 字,大约阅读时间需要 3 分钟。

点击鼠标后,div元素将出现在鼠标点击的位置。实现方式如下:

点击鼠标时,获取鼠标点击位置的坐标,作为div的left和top属性值。需要注意的是,如果div有padding或border,应使用offsetHeight和offsetWidth获取数值,而不是通过getComputedStyle获取。具体实现代码如下:var oDiv = document.querySelector('div');if (!oDiv) {    console.log('未找到div元素');}// 获取鼠标点击位置的坐标window.onclick = function(e) {    const x = e.clientX;    const y = e.clientY;        // 设置div的定位属性    oDiv.style.left = x + 'px';    oDiv.style.top = y + 'px';        // 如果div有padding或border,建议使用以下方式:    // const height = oDiv.offsetHeight;    // const width = oDiv.offsetWidth;    // oDiv.style.left = (x - width / 2) + 'px';    // oDiv.style.top = (y - height / 2) + 'px';        // 示例:让div的中心与鼠标点击位置重合    const height = oDiv.offsetHeight;    const width = oDiv.offsetWidth;    oDiv.style.left = (x - width / 2) + 'px';    oDiv.style.top = (y - height / 2) + 'px';};

以上代码实现了点击鼠标后div元素出现在鼠标点击位置的功能。需要注意的是,如果div有padding或border,建议使用offsetHeight和offsetWidth获取数值,而不是通过getComputedStyle获取。代码中通过获取鼠标点击坐标,拼接px单位,设置div的left和top属性来实现定位。如果需要让div的中心与鼠标点击位置重合,可以在坐标上减去div的宽度和高度的一半。

上一篇:JS-拖拽效果
下一篇:JS-一些标签的禁用等属性

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2025年05月04日 15时48分52秒