简体   繁体   中英

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

I've never triggered multiple events at the same time from an onclick event. 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.

Create a CSS file and set some classes like:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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