Add text and background color to div from html form using jquery
I am trying to add both text color and background color to a hidden div from a form. Once either text or background input fields have been populated, the div should appear with the pre-populated text in the new color and background too. The code is as below:
For the CSS
.testcolor{
width:250px;
height:150px;
border:1px solid #000000;
display:hidden;
}
For the HTML
<form id="myform" action="" method="post">
<input type="text" id="txtcolor" class="tstcolor" name="txtcolor" value="#FF0000">
<input type="text" id="bgcolor" class="tstcolor" name="bgcolor" value="#FFFFFF">
<a href="#" class="preview">Preview</a>
<div class="testcolor">
Lorem ipsum ist nuch nach in die postimen obscurites nang interust ingrostech hochester gelumen bransiolen.
</div>
</form>
For the Javascript
$(document).ready(function(){
$(".tstcolor").keyup(function(){
var txtcolor = $("#txtcolor").val();
var background = $("#bgcolor").val();
$("#txtcolor").css("color",txtcolor);
$("#bgcolor").css("background-color",background);
$('.preview').click(function(){
$("#testcolor").css("visibility","visible");
});
});
});
$(document).ready(function(){
$(".tstcolor").keyup(function(){
var txtcolor = $("#txtcolor").val();
var background = $("#bgcolor").val();
$("#txtcolor").css("color",txtcolor);
$("#bgcolor").css("background-color",background);
});
$('.preview').click(function(){ // Place onclick outside keyup event
var txtcolor = $("#txtcolor").val();
var background = $("#bgcolor").val();
$(".testcolor").css({"background-color":background,"color":txtcolor}).show();//use class selector,i.e (.) for class and (#) for id
});
});
更新了演示
Change
$('.preview').click(function(){
$("#testcolor").css("visibility","visible");
});
to
$('.preview').click(function(){
$(".testcolor").css("visibility","visible");
});
you can use text instead of val
var txtcolor = $("#txtcolor").text;
var background = $("#bgcolor").text;
and
$('.preview').click(function(){
$(".testcolor").css("visibility","visible");
});
链接地址: http://www.djcxy.com/p/70506.html