javascript - 使用下拉菜单更改元素的颜色
问题描述
我想在带有 javascript 的下拉菜单的帮助下更改 svg。
当我想更改段落元素时,我的 javascript 工作正常。然后它清除旧类并根据下拉选项的文本提供一个新类。
但是当我使用它来更改 svg 图像时,它可以随时使用。它为 svg 元素提供了一个新类。但是淘汰旧班级不起作用,然后就坏了。
var selectElem = document.getElementById('select')
var pElem = document.getElementById('p')
// When a new <option> is selected
selectElem.addEventListener('change', function() {
//get value text
var colorValue= document.getElementById('select').options[document.getElementById('select').selectedIndex].text;
pElem.className = '';
// Add that class to the <p>
pElem.classList.add(colorValue);
})
.grün {color: green;}
.gelb {color: yellow;}
.blau {color: blue;}
.rot {color: red;}
.pink {color: pink;}
svg {width: 20%;
height: 20%;}
<p id="p">Element</p>
<select id="select">
<option selected>grün</option>
<option>gelb</option>
<option>blau</option>
<option>rot</option>
<option>pink</option>
</select>
这里 SVG 更改代码:
var selectElem = document.getElementById('select')
var pElem = document.getElementById('one')
// When a new <option> is selected
selectElem.addEventListener('change', function() {
//get value text
var colorValue= document.getElementById('select').options[document.getElementById('select').selectedIndex].text;
pElem.className = '';
// Add that class to the <p>
pElem.classList.add(colorValue);
})
.weiss {fill: white;}
.grün {fill: green;}
.gelb {fill: yellow;}
.blau {fill: blue;}
.rot {fill: red;}
.pink {fill: pink;}
<svg id="one" width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="2" />
</svg>
<p id="p">Element</p>
<select id="select">
<option selected>grün</option>
<option>gelb</option>
<option>blau</option>
<option>rot</option>
<option>pink</option>
</select>
解决方案
您需要更改pElem.className = ''
为pElem.classList = ''
.
var selectElem = document.getElementById('select')
var pElem = document.getElementById('one')
// When a new <option> is selected
selectElem.addEventListener('change', function() {
//get value text
var colorValue= document.getElementById('select').options[document.getElementById('select').selectedIndex].text;
pElem.classList = '';
// Add that class to the <p>
pElem.classList.add(colorValue);
})
.weiss {fill: white;}
.grün {fill: green;}
.gelb {fill: yellow;}
.blau {fill: blue;}
.rot {fill: red;}
.pink {fill: pink;}
<svg id="one" width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="2" />
</svg>
<p id="p">Element</p>
<select id="select">
<option selected>grün</option>
<option>gelb</option>
<option>blau</option>
<option>rot</option>
<option>pink</option>
</select>
这应该可以解决您的问题。
推荐阅读
- html - 使用 VBA 提取一系列 URL
- mysql - 将列添加到 50M+ 记录表?最有效的方法?
- apache - IBM HTTP - http://hostname:port/abc/def/ghi 的 RewriteRule
- prolog - 后缀/前缀如何在 prolog 内部工作?
- javascript - 如何修复 Chart.js 中带有长标签的条形图
- javascript - 如何在 javascript 中深度嵌套的对象成员上使用 Ramda 的 omit() 函数
- php - GROUP BY 重复结果
- xamarin - xamarin 中行为和视图模型之间的通信
- angular - Angular - 表单无效时禁用发送按钮
- angular - 如何使用管道突出显示angular6中的搜索文本?