2015-08-09 48 views
0

我在可汗学院学习JavaScript,需要帮助创建一个收音机类型按钮。对于这段代码,我宁愿不使用html标签。如何使用javascript创建单选按钮(我不想使用html标签)?

我最初有一个表情符号,可以随着mouseX和mouseY动作一起移动。但是,添加按钮功能(工作)后,表情符号不起作用。这似乎是一个或两个案例。有没有办法我可以重新排序我的代码,使两者都有效?

基本上我想要一个与mouseX和mouseY(鼠标的X,Y位置)一起移动的表情符号,并且能够添加一个按钮功能,该功能会向表情符号顶部或底部添加一个圆圈,具体取决于按钮被点击。我希望表情符号在添加圆圈后仍然可以移动。右侧底部的两个矩形是按钮。白色圆圈是表情符号,背景是粉红色的圆圈和粉红色的空白屏幕。

我尝试用drawClick内的mouseClicked或drawExmoji内部或外部的各种组合对代码进行重新排序。但是到目前为止,我还没有找到一种能够提供我所需要的方式的机会。是否有可能使用纯粹的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); 
    } 

}; 

}; 
+0

嗨,欢迎来到SO。请提供一个在线工作的代码示例,例如http://jsfiddle.net,它可以帮助我们为您提供帮助 – JNF

+0

您无法说明“它不工作”以及您希望如何工作。 –

+0

@JNF我已经添加了一个链接 https://www.khanacademy.org/computer-programming/spin-off-of-simple-buttons-with-functionsobject-params/4602551803707392 – quirkypink

回答

0

这个问题是6个月大,但我注意到你还没有从你贴什么改变了这里的代码汗;所以我认为你仍然可能想完成它。

我不会给你特定的代码来解决它(这是你的工作!),但这里有一些指针。

首先,您需要将mouseClicked函数移出绘图函数并完全移除绘图函数。绘制函数在定义时会连续调用,即使在没有鼠标动作发生时也适用于动画。您目前只想在用鼠标进行某些操作时进行绘制。不断绘制是矫枉过正!

其次,添加一个全局变量来指示是否必须绘制圆,如果是,则顶部或底部。在mouseClicked函数中,您不得绘制圆 - 只需将该变量设置为应该的值,并调用背景和表情符号的两个绘制函数即可。

添加mouseMoved函数来调用绘图函数。

在你绘制表情符的函数中,测试你的全局变量来决定在哪里绘制圆(或不绘制它)。

相关问题