简体   繁体   中英

Applying a css gradient to an element dynamically in JQuery

My fiddle - http://jsbin.com/jebusoxa/1/edit

I'm making a simple HSL color picker and dynamically applying a gradient to a range input type on dom ready & element on change to update the picker.

// Setup Code Update
$(".cpick-code-hsl").on('change keyup', function() {
  $(this).val( "hsla(" + $(".cpick-hue-text").val() + ", " + $(".cpick-s-text").val() + ", " + $(".cpick-l-text").val() + ", " + $(".cpick-a-text").val() + ")");

  // Apply as body background
  $(".head").css({
    "background": $(".cpick-code-hsl").val()
  });

  $(".cpick-code-rgb").val( $(".head").css("backgroundColor") );

  // Alpha Saturation
  $(".cpick-s").css({
    "background": "linear-gradient(to right, #7f7f80 0%," + "hsl(" + $(".cpick-hue").val() + "," + $(".cpick-s").val() + "%," + $(".cpick-l").val() + "%)" + " 100%)"
  });
  // Alpha Lightness
  $(".cpick-l").css({
    "background": "linear-gradient(to right, #000000 0%," + "hsl(" + $(".cpick-hue").val() + "," + $(".cpick-s").val() + "%," + $(".cpick-l").val() + "%) 50%,#ffffff 100%)"
  });
  // Alpha Preview
  $(".cpick-a").css({
    "background": "linear-gradient(to right, rgba(51,51,51,0) 0%," + "hsl(" + $(".cpick-hue").val() + "," + $(".cpick-s").val() + "%," + $(".cpick-l").val() + "%)" + " 100%)"
  });
});

I came across the Gradientz plugin, but it's not working on Firefox. Does anyone know of a better and easier solution?

Do you have access to a stylesheet or a <style> element? It would be much easier, more performant, and result in cleaner markup if you defined a css class, then use jQuery to add that class to your element.

http://jsfiddle.net/he3tw/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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