javascript - 为不同的 SVG 应用不同的颜色

标签 javascript jquery html svg

我有一些 svg,我想应用条件来应用颜色,我在 jsfiddle 链接中详细写了

  1. 第一个 SVG 只能应用红色/绿色
  2. 第二个SVG可以应用蓝色/橙色
  3. 第三个SVG可以应用黄色/粉色

http://jsfiddle.net/6w21z1bq/

最佳答案

检查 FIDDLE 上更新的代码 。已对 SVG 标签进行更改,并将 data-index 属性应用于圆圈和按钮。如果选定的圆圈 dta-index 属性与单击的按钮 data-index 属性相同,那么它将应用颜色,否则显示警报。

var clickedPath = '';
var rIndex = '';
$('#select1,#select2,#select3').on("click", function() {
    clickedPath = $(this);
    rIndex = $(this).attr('data-index');
    clickedPath.css({ stroke: "#00ff00" });
});
		
$('.btn').on('click',function(){
    var attr = '';
    attr = $(this).attr('data-index').split(',');
    if($.inArray(rIndex,attr) >= 0 ){
      clickedPath.css({ fill: $(this).attr('data-color') });
    }else{
      alert("Wrong click");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Select SVG and Apply Color <br/>
	
	<svg width="100" height="100">
  	<circle cx="50" cy="50" r="40" stroke="blue" stroke-width="4" fill="yellow" id="select1" data-index = '1' />
  </svg>

  <svg width="100" height="100">
  	<circle cx="50" cy="50" r="40" stroke="yellow" stroke-width="4" fill="red" id="select2" data-index = '2' />
  </svg>
  
  <svg width="100" height="100">
  	<circle cx="50" cy="50" r="40" stroke="blue" stroke-width="4" fill="red" id="select3"  data-index = '3' />
  </svg>


<br/> <br/> 
 
  Apply to Only 1st SVG / For 2nd and 3rd should not be Apply, Alert Box Should Come
  
<button class="btn" id="btn-test1" data-color="#ff0000" data-index = '1,2'>Red</button>
<button class="btn" id="btn-test2" data-color="#00ff00" data-index = '1,2'>Green</button>

<br/> <br/> 

Apply to Only 2nd SVG / For 1st and 3rd should not be Apply, Apply Alert Box Should Come

<button class="btn" id="btn-test3" data-color="#0000ff" data-index = '2,3'>Blue</button>
<button class="btn" id="btn-test4" data-color="#ff9300" data-index = '2,3'>Orange</button>
 
<br/> <br/>

 Apply to Only 3rd SVG / For  3rd and 1st should not be Apply, Apply Alert Box Should Come

<button class="btn" id="btn-test5" data-color="#ffba00" data-index = '3,1'>Yellow</button>
<button class="btn" id="btn-test5" data-color="#ff006c" data-index = '3,1'>Pink</button>

关于javascript - 为不同的 SVG 应用不同的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29271893/

相关文章:

javascript - 识别使用 JQuery 提交的表单

javascript - 将事件类添加到菜单部分

javascript - 在 Firefox 中出现 "undeclared character encoding"错误

javascript - jQuery 确定页面上是否存在元素

javascript - 如何在命令行的每次调用中使用 Webpack 进行增量构建?

javascript - 使用 JQM (jQuery Mobile),为什么 Collapsible 会间歇性地嵌套另一个 collapsible-heading-toggle?

html - YQL查询股票价格

javascript - 如何在Underscore中的 `_.wrap`函数中使用原始参数

javascript - Ember.js "Each"麻烦

javascript - slideToggle() 动画期间出现跨文本换行问题