在下面的代码中,我制作了三个按钮,当您单击它们时它们可以移动,但是如果您在动画期间单击它们,它仍然可以触发 update()
事件。
有没有办法确保在动画播放期间无法按下按钮?
我尝试设置标志来阻止更新,但我无法找到一种无需双击按钮即可使其工作的方法。
另一种选择是使用 setTimeout
,但我不确定这是否会导致一些同步问题。
代码如下:
update(new Date().getFullYear(), 0);
function update(year, speed) {
var t = d3.transition().duration(speed);
var svg = d3.select("svg");
var result = [(year -1).toString(), (year).toString(), (year +1).toString()];
var buttons = svg.selectAll(".button").data(result, d => d)
buttons.exit().transition(t)
.attr("x", d => +d > year ? 240 : -60)
.style("opacity", 0)
.remove()
buttons.enter().append("rect")
.attr("class", "button")
.style("opacity", 0)
.attr("width", 70)
.attr("height", 25)
.attr("y", 15)
.attr("x", d => +d > year ? 240 : -60)
.attr("value", d => d)
.merge(buttons)
.transition(t)
.style("opacity", 1)
.attr("x", (_, i) => 15 + 75 * i)
.attr("fill", d => +d == year ? "#666" : "#ddd")
var onclick = d3.selectAll(".button")
.on("click", function() {
update(+(d3.select(this).attr("value")), 750)
})
}
body {
padding-top: 35px;
margin: auto;
width: 550px;
font: 12px monospace;
}
svg {
width: 250px;
height: 55px;
}
<meta charset="utf-8">
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg class="buttons"></svg>
最佳答案
d3 有相关事件。 (引用:https://github.com/d3/d3-transition/blob/master/README.md#transition_on)
您必须在开始转换时禁用指针事件,然后在转换结束时启用指针事件。 (您还可以在开始和结束时绑定(bind)和取消绑定(bind)点击事件)
检查一下:
update(new Date().getFullYear(), 0);
function update(year, speed) {
var t = d3.transition().duration(speed);
var svg = d3.select("svg");
var result = [(year - 1).toString(), (year).toString(), (year + 1).toString()];
var buttons = svg.selectAll(".button").data(result, d => d)
buttons.exit().transition(t)
.attr("x", d => +d > year ? 240 : -60)
.style("opacity", 0)
.remove()
buttons.enter().append("rect")
.attr("class", "button")
.style("opacity", 0)
.attr("width", 70)
.attr("height", 25)
.attr("y", 15)
.attr("x", d => +d > year ? 240 : -60)
.attr("value", d => d)
.merge(buttons)
.transition(t)
.on("start", function() {
document.getElementById("buttons").style.pointerEvents = "none";
})
.on("end", function() {
document.getElementById("buttons").style.pointerEvents = "all";
})
.style("opacity", 1)
.attr("x", (_, i) => 15 + 75 * i)
.attr("fill", d => +d == year ? "#666" : "#ddd")
var onclick = d3.selectAll(".button")
.on("click", function() {
update(+(d3.select(this).attr("value")), 750)
})
}
body {
padding-top: 35px;
margin: auto;
width: 550px;
font: 12px monospace;
}
svg {
width: 250px;
height: 55px;
}
<meta charset="utf-8">
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg id="buttons" class="buttons"></svg>
关于javascript - 防止动画期间单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53860235/