我有16个三角形,它们在单击button1时分别旋转90度。
因为我有几个执行不同任务的按钮,所以我将所有事件侦听器推入数组,以便可以将其删除和添加。
现在,旋转三角形的功能起作用了。但是每个三角形都在前一个三角形的计数器上不断上升,在第一次单击时始终旋转太多,然后旋转90度。
我在想为每个三角形都需要一个单独的计数器,但是随着代码的设置,我有点迷失了,我不知道什么是最好的方法。
这只是有关的代码
http://jsfiddle.net/antonimoferraz/xcd5wz2e/16
document.getElementById('reflective').addEventListener('click',reflective);
document.getElementById('thinking').addEventListener('click',thinking);
let elementos = document.querySelectorAll('div.elements');
let enhancedElements = [];
let enhancedElementsclick = [];
let degree = 90;
let initial = 0;
// give to each element a separate event handler so it's easy to add and remove when I press different buttons
elementos.forEach(element => {
enhancedElements.push({
element,
mouseenterHandler(){mouseenterHandler(element)},
})
})
elementos.forEach(element => {
enhancedElementsclick.push({
element,
clickHandler(){clickHandler(element)},
})
})
//button n1
//removes event listeners from thinking() and adds its own events
function reflective(){
enhancedElements.forEach(ee => {
ee.element.removeEventListener('mouseenter', ee.mouseenterHandler)
})
enhancedElementsclick.forEach(ee => {
ee.element.addEventListener('click', ee.clickHandler)
console.log(ee.counterfunction);
})
}
//button n2
//removes event listeners from reflective() and adds its own events
function thinking(){
enhancedElementsclick.forEach(ee => {
ee.element.removeEventListener('click', ee.clickHandler)
})
enhancedElements.forEach(ee => {
ee.element.addEventListener('mouseenter', ee.mouseenterHandler)
})
}
//what happens on click
function clickHandler(elementt) {
initial += degree;
elementt.style.webkitTransform = 'rotate('+initial+'deg)';
elementt.style.mozTransform = 'rotate('+initial+'deg)';
elementt.style.msTransform = 'rotate('+initial+'deg)';
elementt.style.oTransform = 'rotate('+initial+'deg)';
elementt.style.transform = 'rotate('+initial+'deg)';
}
function mouseenterHandler(elementt){
// does something else
}
欣赏!
最佳答案
只需将初始值放入元素本身即可:
elementos.forEach(element => {
element.initial = 0; // this line
enhancedElementsclick.push({
element,
clickHandler(){clickHandler(element)},
})
})
然后在处理程序内部,可以使用
elementt.initial
:function clickHandler(elementt) {
elementt.initial += degree;
elementt.style.webkitTransform = 'rotate('+elementt.initial+'deg)';
elementt.style.mozTransform = 'rotate('+elementt.initial+'deg)';
elementt.style.msTransform = 'rotate('+elementt.initial+'deg)';
elementt.style.oTransform = 'rotate('+elementt.initial+'deg)';
elementt.style.transform = 'rotate('+elementt.initial+'deg)';
}
请享用 :)
注意:您不必每次使用另一个数组时都进行循环,而是将它们合并到一个位置:
elementos.forEach(element => {
enhancedElements.push({/*your_data*/})
enhancedElementsclick.push({/*your_data*/})
})