繁体   English   中英

如何仅使用javascript创建单选按钮(我不想使用html标签)?

[英]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

编辑:

到目前为止,这是我的代码:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM