简体   繁体   中英

Change text on parent div on hover?

My idea is that i have something that looks like this in HTML

<h1> A title </h1>

<h2> Under title <h2>
<ul>
<li> something </li>
<li> something else </li>
<li> something third </li>

I wish to do so that when i hover over "something" - there is a hover effect on that item itself, AND the text in "A Title" changes to something else like "This title" ?? and the same for the other list items.

How would you go about this?? I have been searching for various hover states both in CSS and JS.. I am guessing now that it would have to be some kind of JavaScript.

Working demo:

 $('ul').on({ mouseenter: function() { $('h1').text('This title'); }, mouseleave: function() { $('h1').text('A title'); } });
 li:hover { background-color: yellow; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h1> A title </h1> <h2> Under title <h2> <ul> <li> something </li> <li> something else </li> <li> something third </li> </ul>


For the hover effect on the <li>

li:hover {
    background-color: yellow;
}

For the title change :

$('ul').on({
    mouseenter: function () {
        $('h1').text('This title');
    },
    mouseleave: function () {
        $('h1').text('A title');
    }
});

Use the onHover HTML attribute and point it to a Javascript method or code.

HTML:

<h1 id="title" onHover="changeText()>A title</h1>

Javascript:

function changeText(){
    document.getElementById('title').innerHTML = 'You are hovering!';
}

You've tagged with jQuery so lets go with that with a little css. I've also use the HTML Data Attribute to store the title text.

 var initTitle = $("#target").html(); $("ul li").hover(function() { $(this).addClass("active"); $("#target").html($(this).data("title")).addClass("active"); }, function() { $(this).removeClass("active"); $("#target").html(initTitle).removeClass("active"); } );
 /*Change what you want to in here for your hilite effect*/ .active { color: #f00; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <h1 id="target"> A title </h1> <h2> Under title <h2> <ul> <li data-title="First Title"> something </li> <li data-title="Second Title"> something else </li> <li data-title="Third Title"> something third </li> <ul>

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