触发javascript函数onclick

Trigger javascript function onclick

本文关键字:onclick 函数 javascript 触发      更新时间:2023-09-26

我在mudcu的脚本sketch.js.的帮助下创建了一个简单的绘画应用程序

我在代码中做了一些更改,但现在我遇到了触发一个设置铅笔颜色的函数的问题。

var Sketch = function(config) { "use strict";
var that = this;
...........
var ctx2 = layer2d[2];
// Style object.
this.zoom = 1;
this.style = {
    tool: "brush",
    globalAlpha: 1,
    globalCompositeOperation: "source-over",
    strokeStyle: "#000",
    lineWidth: 5,
    lineCap: "round",
    lineJoin: "round"

我的问题是,当用户单击按钮时,我如何将"this.style"strokeStyle设置为例如"#D55151"?

使用JQuery是解决问题的好方法:

<button id="myBtn">My Button</button>

JQuery

$('#myBtn').click(function(){
  // set you style
  that.style.strokeStyle = "#D55151"; // var that = this;
});

更新:

纯javascript的答案:

document.getElementById('myBtn').onclick=function(){
   // set you style
  that.style.strokeStyle = "#D55151"; // var that = this;
};

您可以添加:

function(config, style) {
    this.style = style || this.style = {
            tool: "brush",
            globalAlpha: 1,
            globalCompositeOperation: "source-over",
            strokeStyle: "#000",
            lineWidth: 5,
            lineCap: "round",
            lineJoin: "round"
        };
}

并称之为

$("#somebutton").on("click", function() {
    Sketch({config}, {overides style});
});

如果您使用的是jQuery或下划线,则更好:

function(config, style) {
    this.style = $.extend({
            tool: "brush",
            globalAlpha: 1,
            globalCompositeOperation: "source-over",
            strokeStyle: "#000",
            lineWidth: 5,
            lineCap: "round",
            lineJoin: "round"
        }, style);
}

我更喜欢第二种更安全的解决方案。。。