多行标题背景悬停

  • 本文关键字:悬停 背景 标题 css
  • 更新时间 :
  • 英文 :


我在标题上有一个悬停动画,其中下划线转换为标题的高度。使用:beforeheight设置为3px,然后更改为100%

CSS:

h1 {
  position: relative;
  display: inline-block;
  padding: 0 5px;
}
h1:before {
  content: "";
  height: 3px;
  width: 100%;
  background: crimson;
  position: absolute;
  bottom: 0;
  left: 0;
  display: inline;
  -webkit-transition: height 0.25s;
  -moz-transition: height 0.25s;
  -ms-transition: height 0.25s;
  -o-transition: height 0.25s;
  transition: height 0.25s;
  z-index: -1;
}
h1:hover:before {
  background: crimson;
  height: 100%;
}

它工作得很好,但问题是,当标题有多行时,效果更像是"块"背景,而不是"包裹"在标题周围。我试图通过添加span来实现这一点。下划线是可以解决的,但我仍然无法找到一种方法来改变span上的height,就像我对:before所做的那样。

我不确定这在任何方面是否可行。

CodePen示例:http://codepen.io/semajtwin/pen/htnLy?editors=110

更新

正如coma所建议的那样,添加span解决了这个问题。我添加了一些jQuery来添加span的,使其有点动态。

$(document).ready(function() {
  // get h1
  var h1 = $('h1');
  // split by spaces
  var h1_text = h1.html().split(' ');
  var h1_text_updated = '';
  // for each word
  for (var i=0; i<h1_text.length; i++) {
    //insert span
    var text = h1_text[i];
    // if not last word, add space
    h1_text_updated += (i < h1_text.length-1) ? '<span>' + text + '&nbsp;</span>' : '<span>' + text + '</span>';
  }
  h1.html(h1_text_updated);
});

不过,我认为添加&nbsp;看起来并不是很好。

尝试将span中的每个单词包装以获得正确的高度:

http://jsfiddle.net/coma/19vz9g2y/

<h1>
   <span>Hello</span> <span>World</span>
</h1>

更新

http://jsfiddle.net/coma/19vz9g2y/1/

var apply = function (elements, method) {
    Array
        .prototype
        .forEach
        .call(elements, method);
};
apply(document.getElementsByTagName('h1'), function (h1) {
    h1.innerHTML = h1.innerText.replace(/S+/g, function (word) {
        return '<span>' + word + '</span>';
    });
    var a = -1;
    var lines = [];
    apply(h1.children, function (span) {
        if (span.offsetTop > a) {
            a = span.offsetTop;
            lines.push(span.innerText);
        } else {
            lines[lines.length - 1] += ' ' + span.innerText;
        }
    });
    h1.innerHTML = '<span>' + lines.join('</span><span>') + '</span>';
});

最新更新