javascript 如何从 HTML5 颜色选择器获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13153903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:57:11  来源:igfitidea点击:

How to get a value from HTML5 color picker

javascriptjquery

提问by Alex Hill

I am trying to change the color of an h1 element based on a selection using the color input type, but i cant seem to get it to work. I've tried outputting the color variable to an alert and it only returns undefined.

我正在尝试根据使用颜色输入类型的选择更改 h1 元素的颜色,但我似乎无法让它工作。我试过将颜色变量输出到警报,但它只返回未定义。

 $(function(){

        $("#changeColor").click(function(){

          var color =  $("#colorChoice").value

          $("h1").css("color" + '"' + color + "'")


        });



    });


    </script>


</head>
  <html>
  <body>

  <h1>This is the default text</h1>
  <form>
  <fieldset>
      <select id="changeFont">
        <option>Arial</option>
        <option>Georgia</option>
        <option>Helevtica</option>
    </select>
    <input type="color" id="colorChoice">
    <button id="changeColor" class="btn-primary pull-right">Change</button>
</fieldset>
</form>

回答by Vincent Mimoun-Prat

Try var color = $("#colorChoice").val();See jQuery docs

试着var color = $("#colorChoice").val();jQuery的文档

You might as well bind your callback on the onChange event instead of the onClick event:

您也可以将回调绑定在 onChange 事件而不是 onClick 事件上:

$("#colorChoice").change(function(){
  $("h1").css('background', $(this).val());
});

Working sample

工作样本

回答by user727694

Don't use Jquery for this. vanillaJS works just fine

不要为此使用 Jquery。vanillaJS 工作得很好

document.getElementById("colorChoice").value; 

回答by RushabhG

Your syntax is incorrect.

你的语法不正确。

JavaScript:

JavaScript:

var color = document.getElementById("colorChoice").value;

jQuery:

jQuery:

var color =  $("#colorChoice").val();

I recommend using vanilla JS as it is faster than jQuery.

我推荐使用 vanilla JS,因为它比 jQuery 快。