[英]Creating Concentric Circles with JavaScript/jQuery
我試圖使用for循環使用jQuery從一個對象生成10個同心圓。
我在我的jsfiddle http://jsfiddle.net/JoshuaWaheed/NJkda/2/中寫了這個,看起來像這樣:
<div class="circle"></div>
for(var count = 0; count < 20; count++){
var ten = 10;
ten = ten + 30;
$(".circle").css({"width":ten+"px","height":ten+"px"});
};
我怎么能做到這一點? 當我用任何數字(例如30)添加變量時,它的寬度和高度似乎都會增加,但是沒有顯示它應該的結果。
您需要在循環外定義ten
變量,並為每個環創建一個新元素。
例如,
var ten = 10;
var tgt = $('body');
for(var count = 0; count < 20; count++){
ten += 30;
tgt.append('<div class="circle" style="width:'+ten+'px;height:'+ten+'px;margin:-'+(ten/2)+'px 0 0 -'+(ten/2)+'px"></div>');
};
請注意,我還在javascript中定義了邊距,因為它還需要更改。
你的CSS也需要一點點改變;
.circle {
position: absolute;
top: 50%;
left: 50%;
border: 3px solid #666666;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-border-radius: 100%;
-moz-border-radius: 100%;
border-radius: 100%;
}
我已將邊框半徑設置為100%而不是像素值,並刪除了邊距和寬度/高度,這是不必要的。
首先,將變量聲明移到循環外部。 其次,將border-radius
值設置為50%。 最后,為每個圓創建一個新元素。 您的代碼重新訪問:
/**
* css radius:
* -webkit-border-radius: 50%;
* -moz-border-radius: 50%;
* border-radius: 50%;
*/
var ten = 10;
for(var count = 0; count < 20; count++){
ten = ten + 10;
var c = $('<div class="circle"></div>').appendTo('body');
c.css({"width":ten+"px","height":ten+"px"});
};
修改了jsFiddle
首先,您每個循環重復修改一個現有的圓圈。
其次,每次迭代都要將高度和寬度設置為40px。
第三,你可能想要使用SVG圖形,它為這樣的東西提供原生支持。 以下是SVG的示例:
//HTML
<svg id='circles' xmlns="http://www.w3.org/2000/svg" version="1.1"></svg>
//Javascript
var centerX = 250;
var centerY = 250;
for(var count = 0; count < 20; count++){
var radius = count * 10;
makeAndPlaceCircle(radius);
};
function makeAndPlaceCircle(r){
// thx m93a: http://stackoverflow.com/a/16489845/1380669
var circles = document.getElementById('circles'); //Get svg element
var newElement = document.createElementNS("http://www.w3.org/2000/svg", 'circle');
newElement.setAttribute("cx", centerX);
newElement.setAttribute("cy", centerY);
newElement.setAttribute("r", r);
newElement.style.stroke = "#000"; //Set stroke colour
newElement.style.strokeWidth = "2px"; //Set stroke width
newElement.style.fill = "none"; //Set stroke colour
circles.appendChild(newElement);
};
//No CSS required, but you can define CSS classes and set them on the SVG circle elements, if you would like to e.g. change stroke, fill
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.