문제

I want to add the text from a text field onto another div's style attribute.

For example, there is an input on the page:

<input id="text" />

and a div on the page:

<div id="div1" stlye="background:"></div>

I want what the user inputs in the text_field to show in that div's style. So if a user types the string #FF0000, then I want (in realtime) for the div's style attribute to change to

<div id="div1" style="background:#FF0000"></div>

How can I accomplish this with JavaScript

도움이 되었습니까?

해결책

$('#text').keyup(function () {
    $("#div1").css('background', $('#text').val());
});

다른 팁

Use the change() function like so

$('#inp').keyup(function () {
$("#div1").css('background', $('#inp').val());
});   

with keyup

http://jsfiddle.net/NVW4S/1/

with change http://jsfiddle.net/NVW4S/

I recommend using the jQuery on function:

$('#text').on('keyup', function () {
    $("#div1").css('background', $(this).val());
});

Furthermore, using the same selector instead of this is impractical.

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