我正在使用 tampermonkey 添加一些自定义按钮Unity文档 https://docs.unity3d.com/Manual.
我注意到一个奇怪的问题如果我使用 html<button>
。每次当我单击按钮时,滚动列表就会滚动到顶部,并且代码仅在第二次单击时执行。
但是,如果我更换<button>
with <div>
然后一切都工作得很好。
Why is <button>
行为如此奇怪?
下面是tampermonkey
用于复制的脚本。
// ==UserScript==
// @name Unity Documentation (bugtest)
// @namespace https://docs.unity3d.com
// @version 1.0
// @description test
// @author Edward Black
// @match *://docs.unity3d.com/*
// @grant GM_addStyle
// ==/UserScript==
GM_addStyle('.confirmBox { z-index: 100; width: 275px; background-color: greenyellow; border: 1px solid black; }');
GM_addStyle('.confirmBoxButtons { margin-top: 5px; }');
GM_addStyle('.confirmBoxClose { position: absolute; height: 20px; width: 20px; background-color: white; color:black; border: 0.5px solid black; text-align: center; right: 0px; }');
GM_addStyle('.confirmBoxClose:hover { background-color: black; color:white; cursor: pointer; }');
GM_addStyle('.confirmBoxBtn { background-color: white; color:black; width: 100px; border: 1px solid black; }');
GM_addStyle('.confirmBoxBtn:hover { background-color: black; color:white; cursor: pointer; }');
$(document).ready(function() {
setTimeout(function() {
prepareCustomContextMenue();
$("div.mCSB_container").delegate("#theButton", "click", function() {
alert("Hello from Button");
});
$("div.mCSB_container").delegate("#theDiv", "click", function() {
alert("Hello from Div");
});
$("div.mCSB_container").delegate(".confirmBoxClose", "click", function() {
$(".confirmBox").remove();
});
}, 4000);
});
function prepareCustomContextMenue()
{
$("div.mCSB_container").find("a").each(function(j, obj) {
$(obj).on("contextmenu", function(){
return false;
});
$(obj).on("mousedown", function(e){
if( e.button == 2 ) {
console.log('Right mouse button!');
showConfirmBox(this);
return false;
}
return true;
});
});
}
function showConfirmBox(container)
{
$(".confirmBox").remove();
var elm = '<li><div class="confirmBox">'+
'<div class="confirmBoxClose">x</div>' +
'<div class="confirmBoxButtons">' +
'<button id="theButton" class="confirmBoxBtn"> This is a button </button>' +
'<div id="theDiv" class="confirmBoxBtn"> This is a div </div>' +
'</div>' +
'</div></li>';
$parent = $(container).parent();
$(elm).appendTo($parent);
}
指示
等待站点加载完全(大约4秒直至站点加载指示器消失)然后右键点击在左侧滚动列表中的链接上,该链接应尽可能向下(这样您可以看到单击按钮后列表实际上正在向上滚动)。
现在应该出现一个容器:
现在点击<button>
named This is a button
并注意滚动列表滚动到顶部并且按钮中的代码未执行(应显示警报)。再次按该按钮,您会发现代码现已执行,并且在按警报上的“确定”后,滚动列表再次滚动到顶部。
接下来单击<div>
named This is a div
并注意一切都按预期进行。