仅当光标在 div 内时才可单击按钮

Make button clickable only if cursor inside div

我有一个通过 JS 生成的 div,里面有一个按钮,我只想用鼠标点击它,没有手动 link 以下应该是可能的。

Q1:有没有办法让鼠标光标在div里面的时候按钮才可以点击?

<div class='modal-body' style='padding-top: 10px'>
<a href='?hash="+hash+"' class='btn btn-success btn-xs cbut "+hash+"'><span class='glyphicon glyphicon-forward "+hash+"'></span></a>
</div>

为了防止自动脚本遵循 link,例如 iMacros,我已将 "hash" 变量添加到 link 名称和现在随机的 class 中。 即使这样,他们也可以通过在宏脚本中添加 * 通配符来跟随 link。所以我在这里没有想法。

问题 2:是否有明确的方法来限制 link 仅跟随鼠标?

使用 AddEventListener and the mouseover event 在 div 上添加事件处理程序。

事件触发后,将 href 属性添加到您的 link。并删除 mouseout 上的 attr。

不要使用 <a href inside it>,请使用 javascript onclick,或 jquery on

$('div.modal-body').on('click',function(){
    window.location = "yourlink"
})

可能类似这样的方法可行。 基本上你在每次点击时观察光标位置并检查它是否在 $('#demo-box') 内。否则你可以 e.stopPropagation() and/or e.preventDefault().

不确定这是否有效,因为我不知道宏脚本是否真的会移动鼠标。如果是这样,您可以限制或消除短于 20-30 毫秒的点击。有关去抖动的更多信息 here.

var $demo_box = $('#demo-box');
var demo_box_width: $demo_box.outerWidth();
var demo_box_height = $demo_box.outerHeight();
var demo_box_offset = $demo_box.offset();

$("#button").on('click', function(e) {
    var relativeX = (e.pageX - demo_box_offset.left);
    var relativeY = (e.pageY - demo_box_offset.top);

    if (relativeX > 0 && relativeY > 0 && relativeX < demo_box_width && relativeY < demo_box_height) {
        alert("X: " + relativeX + "  Y: " + relativeY);
    }
});

所以这就是我如何让它为我工作:

1) 将按钮包裹在一个不可见的元素中

2) 删除 link 并通过 onclick 事件添加它

3) 默认禁用按钮

<span style="position:relative;">
<input type="button" onclick="document.location.href='?hash'" class="btn btn-success btn-xs" value="❯❯">
<div style="position: absolute; left: 0px; right: 0px; top: 0px; bottom: 0px; cursor: default; display: none;" id="catch"></div>
</span>

4) 删除不可见元素,该元素也会触发目标中禁用按钮的重新启用 div:

$("#catch").mouseover(function (evt) {
    $(this).hide().prev("input[disabled]").prop("disabled", false).focus();
});

这样,除非将鼠标光标放在按钮上,否则无法再定位或激活该按钮。 我已经击败了当前的 iMacro 脚本,所以现在就可以了。

LE:说得太早了,看来 iMacros 能够很容易地瞄准按钮。但是,我还通过为我的函数添加一个简单的超时来想出一个快速修复方法:

$("#catch").mouseover(function (evt) {
    var $this = $(this)
    setTimeout(function () {
    $this.hide().prev("input[disabled]").prop("disabled", false).focus();
    }, 1000);
});

感谢您在这里提供的所有意见,这让我一直坚持下去。