我在标题上有一个悬停动画,下划线会转换为标题的高度。使用:before
并将height
设置为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
来做到这一点。下划线是可以解决的,但我仍然无法找到一种方法来改变height
上的span
,就像我对:before
所做的那样。
我不确定这是否可行。
CodePen上的示例:http://codepen.io/semajtwin/pen/htnLy?editors=110
更新
根据昏迷添加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 + ' </span>' : '<span>' + text + '</span>';
}
h1.html(h1_text_updated);
});
我认为不过要添加
看起来很棒。
答案 0 :(得分:1)
尝试包装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>';
});