문제

How would you use jQuery to change the value of an object. I have the object and I know the selector, but how would I change the RGB value on click? I'm trying to change the penColor. There are data colors on four list items (yellow, green, blue, orange). So when the user clicks on yellow, the js object changes the object value?

var signaturePad = new SignaturePad(canvas, {
    minWidth: 2,
    maxWidth: 5,
    penColor: "rgb(66, 133, 244)"
});

var selectedColor = $(e.currentTarget).data('color');
$('.initial').css('color', selectedColor);

And here's the markup:

<ul class="global-color">
  <li class="yellow-pick" data-color="#f8c90d"></li>
  <li class="green-pick" data-color="#3dae49"></li>
  <li class="orange-pick" data-color="#e87425"></li>
  <li class="blue-pick" data-color="#009cc5"></li>
</ul>
도움이 되었습니까?

해결책

jsFiddle Demo

You can change the .penColor property of signaturepad during runtime (the API supports this). In order to translate the hex into rgb() you should use the answer linked here by another person as well

hexToRgb adapted from: https://stackoverflow.com/a/5624139/1026459

function hexToRgb(hex) {
 var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
 return result ? "rgb("+parseInt(result[1], 16)+
    ","+parseInt(result[2], 16)+
    ","+parseInt(result[3], 16)+")"
  : null;
}

So using this and assigning the property on click ends up looking like this:

$('.global-color li').click(function(){
 $('.on').removeClass('on');//demo highlighting only
 var $t = $(this);
 $t.addClass('on');//demo highlighting only
 var selectedColor = $t.data('color');//read data
 signaturePad.penColor = hexToRgb(selectedColor);//assign to pen color
});

다른 팁

If you want to change the color of penColor, then you have to expose an method in SignaturePad class something like this

SignaturePad.prototype.setColor(color) {
  this.penColor = color; // Depends on how you have stored penColor internally
}

And call this method from your click handler.

$('.global-color li').click(function(e) {
    var color = e.target.getAttribute('data-color');
    signaturePad.setColor(color);
});

Try this

$('ul.global-color li').click(function(event){
  // Change color here
  var color = $(this).data('color');
  signaturePad.penColor = hexToRGB(color);
}

For a javascript Hex to RGB function I would check out RGB to Hex and Hex to RGB

As mentioned above, you cannot change a property of signaturePad unless there is a method to do so.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top