单击更改CSS属性

我试图在点击另一个元素时更改一个元素的CSS。 我搜索了很多,但没有任何效果。 目前我使用下面的代码,但它不起作用。 谁能告诉我我错过了什么?

hello world!
 function myFunction() { document.getElementById('foo').style.cssText = 'background-color: red; color: white; font-size: 44px'; } 

首先,使用on*属性来添加事件处理程序是实现所需内容的一种非常过时的方式。 正如您使用jQuery标记了您的问题,这是一个jQuery实现:

 
hello world!
 $('#image').click(function() { $('#foo').css({ 'background-color': 'red', 'color': 'white', 'font-size': '44px' }); }); 

一种更有效的方法是将这些样式放入一个类中,然后添加该类onclick,如下所示:

 $('#image').click(function() { $('#foo').addClass('myClass'); }); 
 .myClass { background-color: red; color: white; font-size: 44px; } 
  
hello world!

试试这个:

CSS

 .style1{ background-color:red; color:white; font-size:44px; } 

HTML

 
hello world!

使用Javascript

 function myFunction() { document.getElementById('foo').setAttribute("class", "style1"); } 
     

Javascript Example On click Change Css style


使用jquery,你可以这样做:

 $('img').click(function(){ $('#foo').css('background-color', 'red').css('color', 'white'); }); 

这适用于所有img标签,你应该为它设置一个id属性,如image然后:

 $('#image').click(function(){ $('#foo').css('background-color', 'red').css('color', 'white'); }); 

在你的代码中你不使用jquery,所以,如果你想使用它,你需要像…

 $('#foo').css({'background-color' : 'red', 'color' : 'white', 'font-size' : '44px'}); 

http://api.jquery.com/css/

其他方式,如果你不使用jquery,你需要做…

 document.getElementById('foo').style = 'background-color: red; color: white; font-size: 44px'; 
 
hello world!

JS

 $('#click_me').click(function(){ $('#foo').css({ 'background-color':'red', 'color':'white', 'font-size':'44px' }); }); 

试试这个:

 $('#foo').css({backgroundColor:'red', color:'white',fontSize:'44px'}); 

这段代码似乎工作正常(请参阅此jsfiddle )。 你的javascript是你的身体之前定义的吗? 当浏览器读取onclick="myFunction()"它必须知道myFunction是什么。