包含需要滚动条
的段落的切片DIV
e.g。
<div id="text" style='overflow:scroll;width:200px;height:200px'>
<div style='font-size:64px;'>BIG TEXT</div>
Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text ever
since the 1500s, when an unknown printer took a galley of type and scrambled it
to make a type specimen book. It has survived not only five centuries, but also
the leap into electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of Letraset sheets
containing Lorem Ipsum passages, and more recently with desktop publishing software
like Aldus PageMaker
including versions of Lorem Ipsum.
</div>
当滚动条移动时,文本更改(由于overflow:scroll
),是否可以仅选择当前视图端口中显示的文本?
示例:http://jsfiddle.net/cxgkY/15/
已更新:内部HTML可能包含可变大小的文本
答案 0 :(得分:4)
这是一个应该做你期望的小演示:little link(也适用于可变大小)。我们的想法是为每个单词自动创建单独的span
,然后,每次滚动div
时,检查哪些span
是可见的(通过检查top
{{1}} offset),从而更新文档选择范围。如果有什么不清楚我会很乐意解释它。
答案 1 :(得分:3)
通过仅选择当前视口中的文本不确定您的意思,但可能是这样的:
var elm = $("#text"),
t = $(elm).text().split(' '),
html = [],
selected_text = '';
$.each(t, function(i,e) {
html.push('<span>'+e+'</span>');
});
elm.html(html.join(' '));
$('span', elm).each(function(i,e) {
if ($(e).offset().top < elm.height()) {
$(e).css('background', 'red');
selected_text += $(e).text()+' ';
}
});
如果本练习的目的只是在另一个容器元素中显示文本,你可以按常规方式进行,并伪造它:
$("#text").on('scroll', function() {
$('#visible').html($(this).html()).scrollTop($(this).scrollTop());
});
答案 2 :(得分:0)
可能是这样的(参见DEMO:http://jsfiddle.net/cxgkY/14/):
<强> HTML:强>
<div id="text">
<div id="wrapper">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
</div>
的 JavaScript的:强>
$('#text').scroll(function () {
var text = $(this).text();
var begin = $(this).scrollTop() /
$(this).children('#wrapper').height();
var end = begin + $(this).height() /
$(this).children('#wrapper').height();
var text = text.slice(text.length * begin, text.length * end);
$('#visible').text(text);
});
答案 3 :(得分:0)
<div id="text">
<p>Line 1</p>
<p>Line 2</p>
<p>Line 3</p>
</div>
你可以做..
$(function(){
var meanLineHeight = $('#text > p').first().outerHeight();
var result = $('#result');
$('#text').scroll(function(){
var linesScrolled = Math.ceil(this.scrollTop/ meanLineHeight);
console.log(linesScrolled);
var linesToSelect = $('#text > p').slice(linesScrolled);
linesToSelect.css('background-color', 'yellow');
});
});
<强> DEMO 强>