单击时更改 CSS 属性 [英] Change CSS properties on click

查看:21
本文介绍了单击时更改 CSS 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在单击另一个元素时更改一个元素的 CSS.我已经搜索了很多,但没有什么是完美的.目前我正在使用下面的代码,但它不起作用.谁能告诉我我错过了什么?

<div id="foo">hello world!</div><img src="zoom.png" onclick="myFunction()"/>

function myFunction() {document.getElementById('foo').style.cssText = 'background-color: red;白颜色;字体大小:44px';}

解决方案

首先,使用 on* 属性来添加事件处理程序是一种非常过时的实现您想要的方式.当您使用 jQuery 标记您的问题时,这是一个 jQuery 实现:

hello world!

<img src="zoom.png";id=图像"/>

$('#image').click(function() {$('#foo').css({'背景颜色':'红色','白颜色','字体大小':'44px'});});

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

$('#image').click(function() {$('#foo').addClass('myClass');});

.myClass {背景颜色:红色;白颜色;字体大小:44px;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><div id="foo">你好世界!</div><img src="https://i.imgur.com/9zbkKVz.png?1" id="image"/>

这里有一个简单的 Javascript 实现,供需要的人使用:

document.querySelector('#image').addEventListener('click', () => {document.querySelector('#foo').classList.add('myClass');});

.myClass {背景颜色:红色;白颜色;字体大小:44px;}

<div id="foo">hello world!</div><img src="https://i.imgur.com/9zbkKVz.png?1" id="image"/>

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';
}

解决方案

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'
    });
});

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" />

Here's a plain Javascript implementation of the above for those who require it:

document.querySelector('#image').addEventListener('click', () => {
  document.querySelector('#foo').classList.add('myClass');
}); 

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

<div id="foo">hello world!</div>
<img src="https://i.imgur.com/9zbkKVz.png?1" id="image" />

这篇关于单击时更改 CSS 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆