我如何添加文本到悬停jQuery元素

How do I add li text to an element on hover jQuery

本文关键字:文本 悬停 jQuery 元素 添加 何添加      更新时间:2023-09-26

我想创建一些类似于这个网站的专业知识部分:http://www.theelixirhaus.com/

基本上我只是想要特定的文本出现在图标上面的<h2>当你悬停在他们。每个图标悬停会在同一位置显示不同的文本。我附上了一个JSBin与我所拥有的到目前为止。我不确定li中的<p>是否正确使用,以及如何抓住它并在h2中显示它。

https://jsbin.com/cefuboxoje/edit?html、css、js、输出

demo: http://jsfiddle.net/swm53ran/388/

如果你想保持你原来的使用悬停,使用.hover()代替.on('hover', function() {})

同样,您想使用$(this).find('skills-title').html()来获取<p>标签内的值文本。

我使用了.mouseenter().mouseleave()函数,所以当你不在元素上悬停时,<h4>文本将被清除。

$(document).ready(function() {
    $(".skills").on('mouseenter',function (){
        var title = $(this).find('.skills-title').html();
        $(".title-shown").html(title);
    }).on('mouseleave', function() {
        $(".title-shown").html('');
    });
});

p。在第一个<li>的原始jsbin演示中,您有一个额外的class="skills"。在这种情况下,它不会改变任何东西,只是友好地提醒您检查代码。

你可以使用'mouseover'.children().text()来显示你的文本:

$(".skills").on("mouseover", function (){
  var title = $(this).children().text();
  $(".title-shown").html(title);
});

这是演示!

下面是该行为的简化工作示例:

var $h4 = $('h4');
$('ul').on('mouseover', 'a', function(){
  
  var title = $(this).data('title');
  $h4.stop().fadeIn('fast').text( ': '+ title );
  
}).on('mouseout', function(){
  $h4.stop().fadeOut('fast');
  
});
h3, h4 { display: inline; }
ul li, ul li a { display:inline-block; }
ul li a {
  background: #ddd;
  color: #000;
  padding: 10px;
  text-decoration: none;
  transition: opacity .3s;
  opacity: 0.7;
}
ul li a:hover { opacity: 1; }
<script src='http://code.jquery.com/jquery.js'></script>
  
  <h3>Expertise</h3>
  <h4></h4>
  <ul>
    <li><a href="" data-title="User-centric empowering">One</a></li>
    <li><a href="" data-title="Leading scale deliverables">Two</a></li>
    <li><a href="" data-title="World-class expedite vortals">Three</a></li>
    <li><a href="" data-title="Bleeding-edge whiteboard synergies">Four</a></li>
  </ul>