在 dat.GUI 中,FunctionController
该类负责按钮。如果你看它的源代码,那里没有条件逻辑。控制器将监听click
按钮上的事件,并始终在单击时调用该函数。这意味着您不会从这里的库中获得任何帮助 - 您需要在处理程序中检查按钮是否被禁用。这些方面的东西:
// Find the GUI controller listening to given property on given object
function getController(gui, object, property)
{
for (var i = 0; i < gui.__controllers.length; i++)
{
var controller = gui.__controllers[i];
if (controller.object == object && controller.property == property)
return controller;
}
return null;
}
...
object.button = function()
{
// Don't do anything if the button is disabled
if (getController(gui, this, "button").domElement.hasAttribute("disabled"))
return;
alert("Button clicked");
};
gui.add(object, "button");
...
// Disable button
getController(gui, object, "button").domElement.setAttribute("disabled", "");
请注意,dom.GUI 中的禁用元素没有特殊样式,您必须为此添加自己的样式。鉴于您在按钮的情况下看到的是属性标签而不是实际按钮,这不会很简单 - 我认为您必须将disabled
属性放在controller.domElement.parentNode
而不是controller.domElement
. 然后你应该能够[disabled] > .property-name
为你的样式使用选择器。
编辑:您实际上可以通过扩展以更通用的方式执行此操作FunctionController
:
function blockEvent(event)
{
event.stopPropagation();
}
Object.defineProperty(dat.controllers.FunctionController.prototype, "disabled", {
get: function()
{
return this.domElement.hasAttribute("disabled");
},
set: function(value)
{
if (value)
{
this.domElement.setAttribute("disabled", "disabled");
this.domElement.addEventListener("click", blockEvent, true);
}
else
{
this.domElement.removeAttribute("disabled");
this.domElement.removeEventListener("click", blockEvent, true);
}
},
enumerable: true
});
这将向控制器添加一个属性disabled
,该属性将捕获click
事件,以便不触发按钮处理程序。禁用按钮变得更简单:
getController(gui, object, "button").disabled = true;
并且按钮处理程序可以保持不变,它根本不会被禁用的按钮触发。