单击时更改CSS属性 [英] Change CSS properties on click
本文介绍了单击时更改CSS属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在点击另一个元素时更改一个元素的CSS。我经常搜索,但没有任何效果。目前我使用下面的代码,但它不起作用。谁能告诉我我错过了什么?
I am trying to change the CSS of one element on click of another element. I've searched a lot but nothing works perfectly. Currently I am using the below code, but it doesn't work. Can anyone tell me what I missed?
<div id="foo">hello world!</div>
<img src="zoom.png" onclick="myFunction()" />
function myFunction() {
document.getElementById('foo').style.cssText = 'background-color: red; color: white; font-size: 44px';
}
推荐答案
首先,使用 on *
添加事件处理程序的属性是实现所需内容的一种非常过时的方式。当你用jQuery标记你的问题时,这是一个jQuery实现:
Firstly, using on*
attributes to add event handlers is a very outdated way of achieving what you want. As you've tagged your question with jQuery, here's a jQuery implementation:
<div id="foo">hello world!</div>
<img src="zoom.png" id="image" />
$('#image').click(function() {
$('#foo').css({
'background-color': 'red',
'color': 'white',
'font-size': '44px'
});
});
更有效的方法是将这些样式放入一个类中,然后添加该类onclick,如这个:
A more efficient method is to put those styles into a class, and then add that class onclick, like this:
$('#image').click(function() {
$('#foo').addClass('myClass');
});
.myClass {
background-color: red;
color: white;
font-size: 44px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="foo">hello world!</div>
<img src="https://i.imgur.com/9zbkKVz.png?1" id="image" />
这篇关于单击时更改CSS属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文