[英]Prevent button from being clicked programmatically
我有以下按鈕:
<input type="button" disabled onClick=document.location.href="?hash=blabla" tabindex="-1" class="btn btn-transparent btn-xs cbut0" />
現在該按鈕被禁用並使用另一個腳本在鼠標懸停事件時重新啟用它,但是似乎用戶仍然可以通過加載一個簡單的外部 javascript 以編程方式單擊該按鈕,例如:
window.onload = setTimeout(function(){
$('input.btn.btn-transparent').click();
}, 10000);
有什么辦法可以防止這種行為,以某種方式確保按鈕是由鼠標而不是由某些腳本點擊的?
我發現禁用按鈕上的一些線索仍然使用“.click()”觸發,但在我的情況下未能實現。
您可以使用event
的isTrusted
屬性。 看看MDN 。
Event 接口的 isTrusted 只讀屬性是一個布爾值,當事件由用戶操作生成時為 true,當事件由腳本創建或修改或通過 dispatchEvent 調度時為 false。
function changeHash(event) { if (event.isTrusted) { alert("Trusted"); } else { alert("Programmatically triggered"); } } function triggerClick() { document.getElementById('btn').click(); }
<input type="button" id="btn" onClick="changeHash(event)" tabindex="-1" class="btn btn-transparent btn-xs cbut0" value="change"> <button onclick="triggerClick()">Trigger click</button>
下面是檢查事件是否為可信事件的示例代碼。
if ('isTrusted' in event) {
if (event.isTrusted) {
alert('The ' + event.type + ' event is trusted.');
} else {
alert('The ' + event.type + ' event is not trusted.');
}
} else {
alert('The isTrusted property is not supported by your browser');
}
因此,使用此代碼,您可以像下面一樣更改代碼以使其正常工作。
<input type="button" disabled onClick = "changeHash()" tabindex="-1" class="btn btn-transparent btn-xs cbut0" />
changeHash(event) {
if (event.isTrusted) {
document.location.href = "?hash=blabla"
} else {
event.preventDefault();
}
}
event.isTrusted
解決方法是檢查eventX
和eventY
屬性,如下所示changeHash(event) {
if (event.screenX && event.screenY && event.screenX != 0 && event.screenY != 0) {
document.location.href = '?hash=blabla';
} else {
event.preventDefault();
}
}
嘗試這個:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<title>JS Bin</title>
</head>
<body>
<input type="button" onmousedown="mouseDown()" value="click me" id="btn">
<input type="button" value="Btn2" id="btn2">
<p id="prevented"></p>
</body>
</html>
JS:
function mouseDown() {
alert("MD");
}
$(document).ready(function() {
$("#btn").click(function(evt) {
evt.preventDefault();
//prevented click at time:
$("#prevented").text(new Date());
});
$("#btn2").click(function() {
$("#btn").click();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.