一张图片或Div不同位置点击事件

韩小韩
2021-10-19 / 2 评论 / 363 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2021年10月19日,已超过913天没有更新,若内容或图片失效,请留言反馈。

代码示例

<!--
 * @Author: Han
 * @Date: 2021-10-27 17:34:01
 * @LastEditors: Han
 * @LastEditTime: 2021-10-27 17:36:35
 * @FilePath: \Projectc:\Users\Han\Desktop\Untitled-1.html
-->
<!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>一张图片或Div不同位置点击事件</title>
    <style>
        div {
            position: relative;
            margin: 100px auto;
            width: 332px;
            height: 332px;
            border: 1px solid black;
        }

        div::before,
        div::after {
            content: '';
            position: absolute;
            background: black;
        }

        div::before {
            height: 1px;
            width: 100%;
            top: 166px;
        }

        div::after {
            height: 100%;
            width: 1px;
            left: 166px;
        }
    </style>
    </style>
</head>

<body>
    <div>
    </div>
    <script>
        const btn = document.querySelector('div');
        btn.onclick = function (e) {
            alert(`点击了${e.offsetX >= 166 ? '右' : '左'}${ e.offsetY >= 166 ? '下' : '上'}`)
        };
    </script>
</body>

</html>
2

评论 (2)

取消
  1. 头像
    纬度
    Windows 10 Windows 10 / QQ 浏览器 QQ 浏览器 中国江西省赣州市移动

    这代码高亮不错,是用的插件吗?

    回复
    1. 头像
      韩小韩 作者
      Windows 10 Windows 10 / Google Chrome Google Chrome 中国江苏省南京市电信
      @ 纬度

      Joe主题自带的代码高亮

      回复