Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

html - Change CSS rule at runtime

How do I change any CSS properties during runtime?
Suppose I have:

#mycss {
   background:#000;
   padding:0;
}

Then during runtime, #mycss should be:

 #mycss {
    background:#fff;
    padding:10px;
    }

------------------------**EDIT***-------------------------------------------

Im sorry guys, I'm really new to the HTML world...

My problem or question, whatever that is, I would like to create a piece of code that would change current CSS properties by simply putting a value on the input box (e.g. color: #fff or white) and when I hit the button, it would change the current CSS background color from the default color (#000) to user-defined color (e.g. #fff).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could change it any of the following ways:

  • Adding a style declaration in the page
  • Adding an inline style declaration on the element
  • Using jQuery to change the style of the element

Additional Style Solution:

<style type='text/css'>
    #mycss{ background: #fff; padding: 10px; }
</style>

Inline Style Solution:

Add the following style='background: #fff; padding: 10px' to your element with id='mycss'

jQuery Solution (obviously requires you to include jQuery):

$('#mycss').css('background-color','#FFFFFF').css('padding','10px');

------------------------------------------------------------Edit-----------------------------------------------------------------

Using jQuery - I believe I achieved the functionality you were looking for in your edit. It could be accomplished in pure javascript as well, just let me know if you would like that solution, here is a demo.

Type any color and change the background (Red, #F7F6F5, Purple, #999 etc.)

//On Button Click - changes background on click...
$('#change').click(function()
{
    $('body').css('background-color',$('#color').val()); 
});


//On Textbox Change - changes background when the textbox changes...
$('#color').change(function()
{
         $('body').css('background-color',$(this).val());               
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...