【发布时间】:2021-12-30 19:18:34
【问题描述】:
编辑:扩展 CJMarkham 的答案,我能够通过在他的答案中添加几行 javascript 来实现我所需要的。
这是最终的解决方案:
const buttons = document.querySelectorAll('button')
buttons.forEach((button) => {
button.addEventListener('click', (e) => {
const hex = e.currentTarget.value
const p = document.getElementById("stuff");
p.style.color = hex;
})
})
button {height: 10px; cursor: pointer;}
<div class="container">
<p id="stuff">This text should change color to correspond with the pushed button</p>
</div>
<div class="color-field-widget-box-form" id="color-field-field-link-color">
<button class="color_field_widget_box__square active" value="#5e0dac" color="#5e0dac" title="#5e0dac" style="background-color: rgb(94, 13, 172);"></button>
<button class="color_field_widget_box__square" value="#fc0b22" color="#fc0b22" title="#fc0b22" style="background-color: rgb(252, 11, 34);"></button>
<button class="color_field_widget_box__square" value="#1abe00" color="#1abe00" title="#1abe00" style="background-color: rgb(26, 190, 0);"></button>
<button class="color_field_widget_box__square" value="#283ae5" color="#283ae5" title="#283ae5" style="background-color: rgb(40, 58, 229);"></button>
<button class="color_field_widget_box__square" value="#000000" color="#000000" title="#000000" style="background-color: rgb(0, 0, 0);"></button>
</div>
原文:我有一个带有五个<button>s 的表单元素。由于程序限制,我无法修改任何<button> 属性。所以我不能为每个按钮添加onclick、id 或class 属性。
单击按钮时,我需要将其十六进制值作为内联样式添加到页面上的另一个元素。
由于 JavaScript 知识有限,我知道的唯一方法是将 onclick 属性附加到每个 <button>。但是我无法修改属性,所以我需要另一种方法来定位按钮。
设置如下:
button {height: 10px; cursor: pointer;}
<div class="container">
<p>This text should change color to correspond with the pushed button</p>
</div>
<div class="color-field-widget-box-form" id="color-field-field-link-color">
<button class="color_field_widget_box__square active" value="#5e0dac" color="#5e0dac" title="#5e0dac" style="background-color: rgb(94, 13, 172);"></button>
<button class="color_field_widget_box__square" value="#fc0b22" color="#fc0b22" title="#fc0b22" style="background-color: rgb(252, 11, 34);"></button>
<button class="color_field_widget_box__square" value="#1abe00" color="#1abe00" title="#1abe00" style="background-color: rgb(26, 190, 0);"></button>
<button class="color_field_widget_box__square" value="#283ae5" color="#283ae5" title="#283ae5" style="background-color: rgb(40, 58, 229);"></button>
<button class="color_field_widget_box__square" value="#000000" color="#000000" title="#000000" style="background-color: rgb(0, 0, 0);"></button>
</div>
感谢您的宝贵时间!
【问题讨论】:
标签: javascript html forms button buttonclick