只有当光标位于div内时,才能使按钮可单击

时间:2016-04-14 11:02:46

标签: javascript jquery onmouseover

我有一个通过JS生成的div,其中有一个按钮,我只想用鼠标点击它,不应该有以下手动链接。

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>

为了防止自动脚本跟踪iMacros等链接,我将“hash”变量添加到链接名称和类中,该类现在是随机的。 即便如此,他们也可以通过在宏脚本中添加*通配符来关注链接。所以我在这里没有想法。

Q2:是否有一种明确的方法来限制仅跟随鼠标的链接?

4 个答案:

答案 0 :(得分:1)

使用AddEventListenermouseover event

在div上添加事件处理程序

触发事件时,将href attr添加到&lt; a&gt;链接。并删除mouseout上的attr。

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

这样的事可能有用。 基本上你在每次点击时都会看到光标位置并检查它是否在$('#demo-box')内。否则,您可以e.stopPropagation()和/或e.preventDefault()

不确定这是否有效,因为我不知道宏脚本是否真的会移动鼠标。如果是这样,您可以限制或去除短于20-30ms的点击。关于debouncing 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);
    }
});

答案 3 :(得分:0)

So here's how I made it work for me:

1) Wrap the button inside an invisible element

2) Remove the link and add it via the onclick event

3) Disable the button by default

<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) Remove the invisible element which also triggers the re-enabling of the disabled button from within the target div:

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

This way the button can no longer be targeted or activated unless the mouse cursor is placed over it. I've already beaten current iMacro scripts so this will do for now.

LE: Spoke too soon, seems iMacros was able to target the button quite easily. However I also came up with a quick fix by adding a simple timeout for my function:

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

Thank you for all the inputs here which really kept me going.