我想借助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>
答案 0 :(得分:1)
您需要将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>
这应该可以解决您的问题。