仅当现有填充颜色为特定值时才填充SVG [英] Fill SVG only if existing fill colour is certain value
问题描述
我正在使用此代码更改SVG对象的填充颜色并且它可以正常工作:
I am using this code to change the fill colour of an SVG object and it works:
$(function() {
$('g').mouseenter(function () {
$('path, rect, circle', this).attr('fill', '#00C8C8');
})
});
但是,如果现有填充颜色具有特定值,我只想更改填充颜色。所以,我想到这样的事情:
But, I only want to change the fill colour if the existing fill colour is of a certain value. So, I thought something like this:
$(function() {
$('g').mouseenter(function () {
if($('circle', this).attr('fill') == '#DCDCFF'){
$('circle', this).attr('fill', '#00C8C8');
}
})
});
编辑:...再次,jsfiddle中的轻微错误(感谢Robert)
...again, slight error in the jsfiddle (thanks Robert)
我在jsfiddle上创建了一个页面: http:// jsfiddle。 net / Wc9ZE / 4 /
I've created a page on jsfiddle here: http://jsfiddle.net/Wc9ZE/4/
显示我想要的内容,我也让颜色更加鲜明。
to show what I'm trying to get at, I've also made the colours more distinct.
问题是,所有的矩形变成黄色然后变成红色,我只想要原来是黄色的大矩形变红然后变成黄色。小白色矩形应保持白色。
The problem is, all the rectangles turn yellow then red, I only want the large one that was originally yellow to turn red then back to yellow. The little white rectangle should remain white.
推荐答案
您的括号位置错误
if($('path, rect, circle', this).attr('fill') == '#DCDCFF') {
并且jsfiddle似乎很奇怪,因为在第一个圆圈情况下你使用的是val而不是attr ie
And the jsfiddle seems rather strange as in the first circle case you're using val rather than attr i.e.
if ($('circle', this).val('fill')
应
if ($('circle', this).attr('fill')
不应该吗?
最后如果你只想让它在一个矩形上工作那么你应该给那个rect一个id属性(下面我假设id =r)然后改变这样的代码...
And finally if you only want it to work on one rect then you should give that rect an id attribute (below I've assumed id="r") and then change the code like this...
$(function () {
$('g').mouseenter(function () {
if ($('circle', this).attr('fill') == 'yellow') {
$('circle', this).attr('fill', 'pink');
}
if ($('#r', this).attr('fill') == 'red') {
$('#r', this).attr('fill', 'yellow');
}
}).mouseleave(function () {
if ($('#r', this).attr('fill') == 'yellow') {
$('#r', this).attr('fill', 'red');
}
if ($('circle', this).attr('fill') == 'pink') {
$('circle', this).attr('fill', 'yellow');
}
});
});
这篇关于仅当现有填充颜色为特定值时才填充SVG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!