use js to detect real user click event All In One
使用 js 检测真实的用户点击事件 All In One
<button id="btn" class="btn">Subscribe</button>
<script>
btn.addEventListener('click', (event) => {
console.log('click btn');
// 有一种方法可以区分“真实”用户事件和通过脚本生成的事件 event.isTrusted
if(event.isTrusted) {
console.log('✅ 对于来自真实用户操作的事件,event.isTrusted 属性为 true', event);
} else {
console.log('❌ 对于脚本生成的事件,event.isTrusted 属性为 false', event);
}
});
let click = new Event("click");
btn.dispatchEvent(click);
</script>
<style lang="css">
.btn {
10em;
height: 5ex;
background-image: linear-gradient(135deg, #f34079 40%, #fc894d);
border: none;
border-radius: 5px;
font-weight: bold;
color: white;
cursor: pointer;
}
.btn:active {
box-shadow: 2px 2px 5px #fc894d;
}
</style>
CustomEvent
new CustomEvent(type)
new CustomEvent(type, options)
CustomEvent
只比Event
多了一个 detail 属性,其他属性继承自Event
,故与Event
用法一致!
<button id="rifle">fire </button>
<script>
// create custom events
const fire = new CustomEvent('fire', {
detail: {
id: '007',
name: 'FBI'
},
// options ✅
bubbles: true,
cancelable: true,
composed: true,
});
// add event listener
rifle.addEventListener('fire', (e) => {
const {name, id} = e.detail;
console.log(`${name}-${id} fired `, e)
});
// dispatch `fire` event
rifle.dispatchEvent(fire);
</script>
https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent
new Event(type)
new Event(type, options)
<button id="gun">fire </button>
<script>
// create event
const shot = new Event('shot', {
bubbles: true,
cancelable: true,
composed: true,
});
// add event listener
gun.addEventListener('shot', (e) => {
console.log(`gun fired `, e)
});
// dispatch `shot` event
gun.dispatchEvent(shot);
</script>
https://developer.mozilla.org/en-US/docs/Web/API/Event/Event
https://developer.mozilla.org/en-US/docs/Web/API/Event
demos
<pre id="rabbit">
|\ /|
\|_|/
/. .\
=\_Y_/=
{>o<}
</pre>
<button onclick="hide()">Hide Rabbit</button>
<script>
function hide() {
let event = new CustomEvent("hide", {
cancelable: true,
// 没有这个标志,preventDefault 将不起作用
});
const returnValue = rabbit.dispatchEvent(event);
console.log(`returnValue`, returnValue);
if (!returnValue) {
// 确认阻止,不隐藏,继续显示
alert('The action was prevented by a handler');
} else {
// 取消阻止,隐藏
rabbit.hidden = true;
}
}
rabbit.addEventListener('hide', function(event) {
const flag = confirm("Call event preventDefault?");
console.log('confirm flag', flag);
if (flag) {
// 确定阻止
event.preventDefault();
}
});
</script>
refs
https://zh.javascript.info/dispatch-events#dispatchevent
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 ️,侵权必究⚠️!