似乎所需的行为是更改被点击的原子的atom.name的值,将其替换为下拉菜单中的名称。
例如,点击CH2原子 - >从下拉菜单中选择“Test1” - >您单击的原子的this.name值从“CH2”变为“Test1”。
如果是这种情况,那么问题是如何在atomDropdown的“更改”处理程序中针对最后一个“mouseup”事件中的同一个原子。在这种情况下,您可以在定义中添加新变量:
const canvas = document.createElement('canvas'), context = canvas.getContext('2d'), width = canvas.width = window.innerWidth, height = canvas.height = window.innerHeight, atoms = [], bonds = [], atomDropdown = document.getElementById('atomDropdown') var selectedAtom = null
将selectedAtom设置为“mouseup”处理程序中的atom实例:
document.body.addEventListener('mouseup', e => { let atom = atoms.find(a => distance(a.position, { x: e.pageX, y: e.pageY}) <= a.r) atomDropdown.classList.remove('hidden') if(atom){ selectedAtom = atom atomDropdown.style.left = atom.position.x + 'px' atomDropdown.style.top = (atom.position.y + atom.r) + 'px' } console.log(atom.name);
})
并更新“更改事件”中的selectedAtom.name:
var a = document.getElementById('atomDropdown'); a.addEventListener('change', function() { if (selectedAtom) { selectedAtom.name = this.value; render(); //added so that the GUI updates when the name value changes } console.log(this.value); }, false);
的 编辑: 强> 要立即更新GUI /显示中出现的原子名称,在atomDropDown的“更改”事件中更改selectedAtom.name之后,还必须调用render()。
如果我正确理解这个问题,你是否想要将下拉菜单的值设置为atom.name?
如果是这样,您需要在选项中添加属性“value”,然后您可以这样说:
document.getElementById("atomDropdown").value = atom.name
HTML看起来像这样:
<select id="atomDropdown" class="hidden"> <option value="Na">Test1</option> <option value="Ch2">Test2</option> <option value="O2">Test3</option> </select>