首页 > 解决方案 > 使用下拉菜单更改元素的颜色

问题描述

我想在带有 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>

标签: javascriptjqueryhtmlcsssvg

解决方案


您需要更改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>

这应该可以解决您的问题。

链接:className 文档classList 文档

相关标签: , ,


推荐阅读