簡體   English   中英

僅當光標位於div內時,使按鈕可單擊

[英]Make button clickable only if cursor inside div

我有一個通過JS生成的div,其中有一個按鈕,我只想用鼠標單擊即可,后面沒有任何手動鏈接。

問題1:是否只有在鼠標光標位於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:是否有確定的方法將鏈接限制為僅鼠標以下?

使用AddEventListenermouseover事件在您的div上添加事件處理程序。

觸發事件后,將href屬性添加到您的<a>鏈接。 並在mouseout上刪除attr。

不要使用<a href inside it> ,使用JavaScript onclick ,或jQuery的on

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

大概這樣的事情可能會起作用。 基本上,您會觀察每次單擊的光標位置,並檢查它是否在$('#demo-box') 否則,您可以e.stopPropagation()和/或e.preventDefault()

不知道這是否行得通,因為我不知道宏腳本是否真正移動了鼠標。 如果是這樣,您可以在20到30毫秒之內縮短或消除咔嗒聲。 有關在此處彈跳的更多信息。

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)刪除鏈接並通過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);
});

感謝您在這里的所有投入,這確實讓我前進。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM