使用:first-line伪元素作为jQuery选择器 [英] Use :first-line pseudo-element as a jQuery selector
问题描述
我知道我可以使用CSS :first-line
伪元素来定位和更改任何文本块中第一行的样式(例如在此演示中:
I know I can use CSS :first-line
pseudo-elmenent to target and change style of the first line in any block of text (like in this demo: http://jsfiddle.net/6H8sy/). So the first line can be found and targeted.
我想知道是否有任何方法可以选择该文本重新使用.像$(':first-line')
之类的东西(实际上不能正常工作).
I was wondering if there's any way to actually select that text to reuse. Something like $(':first-line')
(which doesn't work as it is).
推荐答案
由于您无法选择伪元素本身,因此可以复制:first-line
的行为来确定文本.我写了一个快速的JS函数,类似于一个 @凯文B建议.如果仅存在一行文本,此函数将首先确定元素的高度.然后使用for
循环从文本节点中删除单词,直到元素的新高度等于初始高度.然后该函数返回first-line
文本.
Since you can't select the pseudo element itself, you could replicate the behavior of :first-line
, to determine the text. I wrote a quick JS function, similar to the one @Kevin B suggests. The function initially determines the height of the element if there is only one line of text present. A for
loop is then used to remove a word from the text node until the element's new height equals the initial height. The function then returns with the first-line
text.
> 此处的示例 -该函数在onLoad上运行,因此,如果窗口的宽度变化,文本显然与first-line
不匹配.您可以通过在调整屏幕大小时运行该功能来轻松解决此问题.
Example Here - the function is run onLoad, therefore if the window's width changes, the text obviously won't match first-line
. You could easily fix this by running the function when the screen is resized.
JavaScript函数-没有jQuery
JavaScript function - no jQuery
function first_line(element) {
var el = document.getElementById(element), cache = text = el.innerHTML;
el.innerHTML = 'a'; var initial = el.offsetHeight; el.innerHTML = cache;
arr = text.split(" ");
for (var i = 0; i < arr.length; i++) {
text = text.substring(0, text.lastIndexOf(" "));
if (el.offsetHeight == initial) {
var temp = el.innerHTML;
el.innerHTML = cache;
return temp;
}
el.innerHTML = text;
}
}
我不知道我是否在这里重新发明轮子;但这确实有效.我不知道能够实现此目标的任何jQuery或内置JS.不管浏览器支持如何,这也应该在没有任何跨浏览器样式不一致的情况下起作用. 似乎可以与任何类型的填充/边框一起使用. (示例)
I don't know if I'm re-inventing the wheel here, or not; but this does work. I'm not aware of any jQuery or built-in JS that is able to achieve this. Disregarding browser support, this should also work without any cross-browser styling inconsistencies. It seems to work with any types of padding/borders. (example)
这篇关于使用:first-line伪元素作为jQuery选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!