Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[html] 24. 如何在页面上实现一个圆形的可点击区域? #45

Open
qiilee opened this issue Sep 29, 2019 · 0 comments
Open
Labels

Comments

@qiilee
Copy link
Member

qiilee commented Sep 29, 2019

答案:css3、js、map 加 area

一.border-radius (css3)

对于圆形,最直接的方法想到的就是 css3 的圆角属性,这个属性可以将 html 元素的形状设置为圆形,这之后你想对该圆形区域设置什么事件就设置什么事件(当然包括点击)。(这里就不做具体的 test 了)

二.通过事件坐标来实现(js)

也就是通过 js 来进行一个区域判断,进而简介地的形成可点区域,以下给出主要的 js 测试代码:

// 获取目标元素
var box = document.getElementById("box");

// 对目标元素target的圆形区域进行一个点击事件绑定
function bindClickOnCircleArea(target, callback) {
  target.onclick = function(e) {
    e = e || window.event;

    // target中心点的坐标
    var x1 = 100;
    var y1 = 100;

    // 事件源坐标
    var x2 = e.offsetX;
    var y2 = e.offsetY;

    // 校验是否在圆形点击区,在的话就执行callback回调
    // 计算事件触发点与target中心的位置
    var len = Math.abs(Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)));
    // 通过半径进行校验
    if (len <= 100) {
      callback();
    } else {
      alert("死鬼,跑哪去啊,你老婆我是黄皮肤还是白皮肤都分不清了吗");
    }
  };
}

// 执行
bindClickOnCircleArea(box, function() {
  alert("老婆,你让我好找啊,呜呜呜");
});

三.通过 map 加 area

<img src="../imgs/test.jpg" width="200" border="0" usemap="#Map" />
<map name="Map" id="Map">
  <area
    shape="circle"
    coords="100,100,100"
    href="http://www.baidu.com"
    target="_blank"
  />
</map>

参考

@qiilee qiilee added the HTML label Sep 29, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant