首页 > 如何做到只点击 div border-radus:50% 的圆形区域

如何做到只点击 div border-radus:50% 的圆形区域


#circle{ width: 100px;height: 100px; background-color: red; border-radius: 50%;}

我只想点击红色区域时才触发事件,但是现在点击四角也会触发点击事件,该怎么办..


这个可能和浏览器有关,比如我的浏览器就只有点击中心有效(当然也有可能是和 jQuery 有关)

来个效果:http://jsfiddle.net/q9nwqjub/1/

主要思想,判断点击位置到圆心的距离,如果在半径范围内,就说明点击在圆上。代码示例

$("#circle").on("click", function(e) {
    var circle = $(this);
    var width = circle.width();
    var harf = width / 2;
    
    // 算点击位置到圆心的距离
    var distance = Math.sqrt(
        Math.pow(e.offsetX - harf, 2)
        + Math.pow(e.offsetY - harf, 2));

    console.log(distance);
    if (distance > harf) {
        console.log("ok");
        return;
    }
    
    console.log("do what you want");
    // 这里干正事,下面只是个示例
    circle.css("background-color", "blue");
    setTimeout(function() {
        circle.css("background-color", "red");
    }, 1000);
});

还可以两层div 一层用来控制形状 一层用来绑定事件


overflow:hidden

【热门文章】
【热门文章】