简体   繁体   English

使用jQuery根据输入字段值更新backgroundColor LIVE?

[英]Updating backgroundColor LIVE based upon an input field value using jQuery?

I'm building a little script that changes content and css live on the page based upon the values of various input fields. 我正在构建一个小脚本,该脚本根据各种输入字段的值更改页面上的内容和CSS。

I'm able to change the content "live" absolutely fine as you'll see here: http://jsfiddle.net/tctc91/eQwsE/ 我可以将内容“实时”更改为完全正常,如您在此处看到的: http : //jsfiddle.net/tctc91/eQwsE/

I'm not able to get this working with the css method using the same principles though: http://jsfiddle.net/tctc91/Tnc8p/ 我无法使用相同的原理使用CSS方法进行此操作: http : //jsfiddle.net/tctc91/Tnc8p/

Thanks! 谢谢!

Replace the second bgColor with $(this).val() . 将第二个bgColor替换为$(this).val()

You have assigned the starting value to bgColor , and then you never reassign a new value to it. 您已将初始值分配给bgColor ,然后再也不会bgColor分配新值。

jsFiddle . jsFiddle

You just have to define the bgColor variable after the user inputs it. 用户输入后,只需定义bgColor变量即可。 Here's a fiddle that does just that. 这是一个小提琴。

What I've done is copy the bgcolor variable and placed it once again inside the keyup function. 我所做的是复制bgcolor变量,并将其再次放入keyup函数中。 This way, it defines the variable again after a key is pressed. 这样,它按下某个键再次定义了变量。

The fiddle works perfectly. 小提琴运作完美。

You're forgetting to re-set the bgcolor variable whenever you change the input: 每当您更改输入时,您都忘记了重新设置bgcolor变量:

Try this: 尝试这个:

$(function() {
    var bgColor = $('#colorpickerField1').val();   
    $('body').css("backgroundColor",'#' + bgColor);

    $('#colorpickerField1').change(function() {
       var bgColor = $('#colorpickerField1').val();
       $('body').css("backgroundColor",'#' + bgColor);
    });
});

You have to set bgColor 's value again. 您必须再次设置bgColor的值。 I also added a little check if it's length is 3 or 6 chars. 我还添加了一点检查,如果它的长度是3或6个字符。

$(function() {
    var bgColor = $('#colorpickerField1').val();   
    $('body').css("backgroundColor",'#' + bgColor);

    $('#colorpickerField1').keyup(function() {
       bgColor = $('#colorpickerField1').val();
        if(bgColor.length ==3 || bgcolor.length == 6) {
            $('body').css("backgroundColor",'#' + bgColor);
        }
    });
});

You need to retrieve the .val() of the field inside the .keyup() handler, as the value will always be changing every time the user presses a key. 您需要检索.val() 场的.keyup()处理程序,为价值总是会改变用户每按下一个键的时间。

Change your javascript to: 将您的JavaScript更改为:

$(function() {
    var bgColor = $('#colorpickerField1').val();   
    $('body').css("backgroundColor",'#' + bgColor);

    $('#colorpickerField1').keyup(function() {       
       $('body').css("background-color",'#' + $(this).val());
    });
});

Updated jsFiddle: http://jsfiddle.net/Tnc8p/1/ 更新的jsFiddle: http : //jsfiddle.net/Tnc8p/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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