[英]How to change the color of an SVG circle fill color using jQuery dynamically
[英]How to change SVG fill color on second click jquery
我正在嘗試在第二次單擊時更改 SVG 上的填充顏色,目前,可以在第一次單擊時添加填充顏色,但我希望在第二次單擊時顏色更改/重置為默認值; 這是我當前的代碼:
jQuery('#color-my-svg').on("click", function() {
if(!jQuery(this)[0].hasAttribute('style')){
jQuery('#color-my-svg').css({ fill: "#ff0000" });
}
else{
jQuery(this).removeAttr('style');
}
});
每當用戶點擊元素時:
如果元素具有 class 標識符,則更改填充顏色(例如
click-one
)。
否則添加 class 標識符。
jQuery('#color-my-svg').on("click", function() {
if(jQuery('#color-my-svg').hasClass("click-one"))
jQuery('#color-my-svg').css({ fill: "#ff0000" });
else
jQuery('#color-my-svg').addClass("click-one");
});
您可以將點擊計數器設置為variable
並根據點擊次數檢查添加/刪除 class,如下所示:
HTML:
<div id="divId" class="divClass">I'm a div!</div>
CSS:
/* Styling for demo only */
.divClass {
background: green;
color: white;
height: 100px;
width: 100px;
}
.svg-fill-color {
background: red;
/* Add fill here */
}
JavaScript:
let clickNumbers = 0;
jQuery('#divId').on("click", function() {
clickNumbers++;
if(clickNumbers % 2 == 0){
jQuery('#divId').addClass('svg-fill-color');
} else {
jQuery('#divId').removeClass('svg-fill-color');
}
});
您可以在此處查看示例代碼。
讓我知道,如果這有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.