Jef*_*ohl 7 javascript dat.gui
我试图找到一种方法来轻松禁用/启用dat.gui中的按钮.
我有dat.gui设置来控制动画.当动画结束时,我希望"播放"按钮被禁用.我已经尝试将"禁用"属性添加到按钮的DOM元素,但是在设置此属性后单击按钮时,我仍然看到相应的函数触发.
我目前的方法如下:
li与dat.gui界面中的按钮对应的元素li元素内添加此元素以使按钮的内容变灰.这是一个hack,我很想知道是否有一些方法可以禁用内置于dat.gui中的按钮,或者是一些我不知道的更好的方法.
在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", "");
Run Code Online (Sandbox Code Playgroud)
请注意,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
});
Run Code Online (Sandbox Code Playgroud)
这将向disabled控制器添加一个属性,该属性将捕获click事件,以便不触发按钮处理程序.禁用按钮变得更简单:
getController(gui, object, "button").disabled = true;
Run Code Online (Sandbox Code Playgroud)
按钮处理程序可以保持不变,对于禁用的按钮,它不会被触发.