简体   繁体   English

JavaScript:触发多个事件?

[英]JavaScript: Triggering Multiple Events?

I want to finish this project I was working on for my mom for Valentine's day.我想完成这个我在情人节那天为我妈妈做的项目。

I want to be able to click an h2 and have it trigger multiple events, for example making the background color green, changing the font size of h2 to something bigger like 50px and changing the font size of h1 to 50px我希望能够点击一个h2并让它触发多个事件,例如将背景颜色设为绿色,将h2的字体大小更改为 50px 之类的更大的大小,并将h1的字体大小更改为 50px

I've never triggered multiple events at the same time from an onclick event.我从来没有从一个 onclick 事件同时触发多个事件。 I'd love assistance to make mom happy.我很乐意帮助让妈妈开心。

 body { background-color: lightblue; }
 <html> <body> <h1 style="color:purple; text-align:center;" onclick="this.style.color='yellow'; this.style.fontSize='40px'; document.body.style.backgroundColor='green';"> Happy Valentines Day Mom! </h1> <img src="Source/me.jpg" alt="This is Me" width="300" height="300" align="middle"> <p align="center" style="color:white;" onmouseover="this.style.textDecoration='underline';" onmouseout="this.style.textDecoration='';"> Lots of love and wishes on this day. It is not possible to repay the love that you have given to me. I just can love you, dear mom. Take my lots of love on this Happy Valentine's Day. </p> <img src="source/mom.jpg" alt="Mom" width="200" height="200" align="middle"> <h1 style="color:blue; text-align:center;" onclick="this.innerHTML='Best Mother Ever!';"> I love you so much! - J </h1> <br> <h2 id="joke" align="center" style="color:white;" onmouseover="this.style.textDecoration='line-through';" onmouseout="this.style.textDecoration='';">PS I love you more!</h2> <button type="button" onclick='document.getElementById("joke").innerHTML = "PSS you are the best!"'>Click Me!</button> </body> </html>

I think it would be best to work with style using a CSS file.我认为最好使用 CSS 文件处理样式。

Create a CSS file and set some classes like:创建一个 CSS 文件并设置一些类,例如:

h2.valentines {
    background-color: green;
    font-size: 50px;
    color: white;
}

Then on the onclick event you can pass a function to add the class to the element you want, just like this:然后在onclick事件上,您可以传递一个函数将类添加到您想要的元素,就像这样:

function addValentineClass() {
    const element = document.getElementById('joke');
    element.className = "valentines";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM