[英]How to create a radio button using only javascript (I don't want to use html tags)?
我在Khan Academy學習javascript,需要幫助來創建單選按鈕。 對於此代碼,我寧願不使用html標簽。
我最初有一個表情符號,它會隨着mouseX和mouseY的移動而移動。 但是,添加按鈕功能(有效)后,表情符號不起作用。 這似乎是一種情況。 有沒有一種方法可以重新排序我的代碼,使兩者都能正常工作?
基本上,我想要一個隨mouseX和mouseY(鼠標的X,Y位置)移動的表情符號,並且能夠添加按鈕功能,該功能會根據單擊的按鈕在表情符號的頂部或底部添加一個圓圈。 我希望表情符號在添加圓圈后仍然能夠移動。 右邊底部的兩個矩形是按鈕。 白色圓圈是表情符號,背景是粉紅色圓圈和粉紅色空白屏幕。
我嘗試在繪圖中,其外部或在drawEmoji中使用mouseClicked的各種組合對代碼進行重新排序。 但是到目前為止,我還沒有找到能滿足我需求的方法。 是否可以使用純JavaScript來做到這一點? TIA
編輯:
這是我在我的代碼上工作的地方的鏈接。 我沒有將它放在jsfiddle中,因為我還不知道如何使用html標記並向其中添加代碼。 https://www.khanacademy.org/computer-programming/spin-off-of-simple-buttons-with-functionsobject-params/4602551803707392
至於解釋我想發生的事情,那是我帖子的第3段? 如果還不清楚,請告訴我。
到目前為止,這是我的代碼:
var x = 250;
var y = 300;
var btnwidth = 100;
var btnheight = 30;
//to highlight the button that is pressed
var highlightbox = function(hix, hiy, hiw, hih) {
noFill();
stroke(56, 247, 8);
strokeWeight(5);
rect(hix, hiy, hiw, hih);
};
//outer circle of the emoji face, the idea was for it to move along with the mouse but now it doesn't
var X = constrain(mouseX, 190, 210);
var Y = constrain(mouseY, 115, 140);
var W = 160;
var H = W;
var drawEmoji = function() {
var X = constrain(mouseX, 190, 210);
var Y = constrain(mouseY, 115, 140);
var W = 160;
var H = W;
fill(247, 242, 242);
stroke(0, 51, 255);
strokeWeight(3);
ellipse(X,Y,W,H);
};
//background behind the emoji
var drawBackground = function() {
background(250, 187, 187);
fill(191, 130, 130);
stroke(255, 0, 0);
strokeWeight(3);
ellipse(200,200,400,400);
fill(247, 207, 247);
rect(x, y, btnwidth, btnheight);
fill(173, 207, 250);
rect(x, y+50, btnwidth, btnheight);
};
drawBackground();
drawEmoji();
var draw = function() {
//mouse click function for the button, when it's clicked a circle appears on the emoji
mouseClicked = function(){
drawBackground();
drawEmoji();
if (mouseX > x && mouseX < (x + btnwidth) && mouseY > y && mouseY < (y + btnheight)) {
highlightbox(x, y, btnwidth, btnheight);
stroke(68, 0, 255);
fill(247, 207, 247);
ellipse(X - 49,Y - 50,W/3,H/3);
}
else if (mouseX > x && mouseX < (x + btnwidth) && mouseY > y + 50 && mouseY < (y + 50 + btnheight)) {
highlightbox(x, y + 50, btnwidth, btnheight);
stroke(68, 0, 255);
fill(173, 207, 250);
ellipse(X+1,Y+100,W/3,H/3);
}
};
};
這個問題已有6個月了,但我在Khan上注意到您尚未更改此處發布的代碼; 因此,我認為您可能仍想完成它。
我不會為您提供特定的代碼來修復它(這是您的工作!),但是這里有一些指針。
首先,您需要將mouseClicked函數從繪制函數中移出並完全刪除繪制函數。 繪制函數在定義后會連續調用,即使沒有鼠標動作也可以用於動畫。 當前,您只想在使用鼠標進行某些操作時進行繪制。 不斷畫畫是太過分了!
其次,添加一個全局變量以指示是否必須繪制圓,如果需要繪制圓,則指示頂部或底部。 在mouseClicked函數中,您不必繪制圓-只需將此變量設置為應該的大小,然后調用背景和表情符號這兩個繪制函數即可。
添加mouseMoved函數以調用繪圖函數。
在表情符號的繪制功能中,測試您的全局變量,以決定在何處繪制圓形(或不繪制圓形)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.