简体   繁体   English

通过下拉菜单设置SVG元素的样式

[英]Styling an SVG element via Drop Down Menu

I have a SVG floor plan, and I trying to add a drop down menu that will let people select a location to have it appear on the map. 我有一个SVG平面图,并且尝试添加一个下拉菜单,该菜单可使人们选择要在地图上显示的位置。 I have very little experience with jQuery, but this is what I've been able to put together from code I've found while googling: 我对jQuery的经验很少,但这是我在谷歌搜索时发现的代码中能够汇总的内容:

 $(function() { $('select').change(function() { var s = $(this).find('option:selected').text(); if(s == "Left") { $('#rleft').css('fill', 'green'); } else if(s == "Middle") { $('#rmiddle').css('fill', 'orange') } else if(s == "Right") { $('#rright').css('fill', 'red') } }); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option value="blank">Select a Location</option> <option value="left">Left</option> <option value="middle">Middle</option> <option value="right">Right</option> </select> <svg height="170" width="500"> <rect id="rleft" x="10" y="10" width="150" height="150" fill="#FFFFFF" stroke="#000000" /> <rect id="rmiddle" x="170" y="10" width="150" height="150" fill="#FFFFFF" stroke="#000000" /> <rect id="rright" x="330" y="10" width="150" height="150" fill="#FFFFFF" stroke="#000000" /> </svg> 

As it is now, the drop down will change colors, but I'd like the previous selection to be cleared when a new option is selected. 现在,下拉菜单将更改颜色,但是我希望在选择新选项时清除先前的选择。 Only one square should have color at a time. 一次只能有一个正方形具有颜色。 I have a feeling it is something I'm overlooking. 我觉得这是我忽略的事情。 I would appreciate any help. 我将不胜感激任何帮助。 Thank you. 谢谢。

You have to remove the style (eg set fill:none) for the other elements when the value changes. 当值更改时,您必须删除其他元素的样式(例如,设置fill:none)。

$(function() {
  $('select').change(function() {
    var s = $(this).val();
    $('#rleft').css('fill', s == "left"?'green':'none');
    $('#rmiddle').css('fill', s == "middle"?'orange':'none');
    $('#rright').css('fill', s == "right"?'red':'none');
  })
})

When one of the squares is selected you need to reset the color of the other squares to #FFF. 选择一个正方形后,您需要将其他正方形的颜色重置为#FFF。

Something like this: 像这样:

 if (s == "Left") { $('#rleft').css('fill', 'green'); // set colors back to white $('#rmiddle').css('fill', '#FFF'); $('#rright').css('fill', '#FFF'); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM